Reputation: 3
I am trying to build a Python application for running in various platforms, for that I am adding command line options for parameters, two of which is username and password. For password, I don't want it to be echoed on screen while someone is entering it, I am using argparse
Sample code-
parser.add_argument('--username', help='Your email address')
parser.add_argument('--password', help='Your password')
Now what parameter/action I should add to make password invisible/not echoed on screen while entering it?
Upvotes: 0
Views: 927
Reputation: 376
In python, we can use getpass as below :
>>> import getpass
# parse arguments here
>>> user = args.username # e.g. Sam
>>> password = getpass.getpass('Enter %s password: '% user)
Enter Sam password:
>>>
What you want to do is this,
class Password(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
values = getpass.getpass()
setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser()
parser.add_argument('--password', action=Password, nargs='?', dest='password')
args = parser.parse_args()
password = args.password
Upvotes: 2