How to suppress the display of passwords?

oxana picture oxana · Apr 29, 2015 · Viewed 7.4k times · Source

I need to hide password when user run script in console (like this: mysql -p). For input parameters I use argparse, how I can add getpass to password parameter?

parser = argparse.ArgumentParser()
parser.add_argument('-p', action='store', dest='password', type=getpass.getpass())

When I run my script: python script.py -u User -p I get separate line for enter password (Password:), but after entering Exception: ValueError: 'my_password' is not callable is raised.

Answer

qwattash picture qwattash · Apr 29, 2015

This guy should solve your problem: getpass

Here is an example with a custom action

class PwdAction(argparse.Action):

     def __call__(self, parser, namespace, values, option_string=None):
         mypass = getpass.getpass()
         setattr(namespace, self.dest, mypass)

parser = argparse.ArgumentParser()
parser.add_argument('-f', action=PwdAction, nargs=0)