Python: Using getpass with argparse

MHibbin picture MHibbin · Jan 13, 2015 · Viewed 12.4k times · Source

I've had a look around, but couldn't find anything.

Basically I was wondering if it was possible to use getpass.getpass() with argparse.

At the moment I have the following as a work around, I was just wondering if there was a better way:

import argparse
import getpass

parser = argparse.ArgumentParser(description="Some description")
parser.add_argument('-p', metavar="password", default="foobarblah123", help="password for user (default to prompt user)")
...
parsed_args = parser.parse_args()
args = vars(parsed_args)
user_pass = args['p']
if user_pass == "foobarblah123":
  user_pass = getpass.getpass()

I'm pretty sure this is not the best way to handle this, however, there is a requirement to have a command line option for the password ... best practice or not.

Thanks.

Answer

Rares Musina picture Rares Musina · Feb 19, 2015

I think I might have found a nicer way to do it. How about using a custom Action like this:

import argparse
import getpass

class PasswordPromptAction(argparse.Action):
    def __init__(self,
             option_strings,
             dest=None,
             nargs=0,
             default=None,
             required=False,
             type=None,
             metavar=None,
             help=None):
        super(PasswordPromptAction, self).__init__(
             option_strings=option_strings,
             dest=dest,
             nargs=nargs,
             default=default,
             required=required,
             metavar=metavar,
             type=type,
             help=help)

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

parser.add_argument('-u', dest='user', type=str, required=True)
parser.add_argument('-p', dest='password', action=PasswordPromptAction, type=str, required=True)

args = parser.parse_args()