简体   繁体   中英

Is there method such that password won't be echoed on cmd while passing it as command line argument?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM