Python argparse - either both optional arguments or none

I have a program that uses the default username and password. I use argparse to allow the user to specify command line options, and I would like to enable the user to provide the program with a different username and password to use. Therefore, I have the following:

parser.add_argument( '-n', '--name', help='the login name that you wish the program to use' ) parser.add_argument( '-p', '--password', help='the password to log in with.' ) 

But it makes no sense to specify only a name or only a password, but it would be pointless to specify any. I noticed that argparse has the ability to indicate that the two arguments are mutually exclusive. But I have two arguments that should come together. How do I get this behavior? (I found the “argument groups” mentioned in the docs, but they don't seem to solve my problem http://docs.python.org/2/library/argparse.html#argument-groups )

+20
python command-line-arguments argparse
Jan 16 '13 at 2:10
source share
3 answers

I believe the best way to handle this is to handle the returned namespace. The reason argparse does not support this is because it parses arguments 1 at a time. It's easy for argparse to check if something has already been parsed (that's why mutually exclusive arguments work), but it's not easy to see if something will be sorted out in the future.

Simple:

 parser.add_argument('-n','--name',...,default=None) parser.add_argument('-p','--password',...,default=None) ns = parser.parse_args() if len([x for x in (ns.name,ns.password) if x is not None]) == 1: parser.error('--name and --password must be given together') name = ns.name if ns.name is not None else "default_name" password = ns.password if ns.password is not None else "default_password" 

it seems that this will be enough.

+17
Jan 16 '13 at 2:21
source share

I know that more than two years have passed, but I found a good and concise way to do this:

 if bool(ns.username) ^ bool(ns.password): parser.error('--username and --password must be given together') 

^ is an XOR operator in Python. Require both arguments given on the command line to be basically an XOR test.

+6
Oct 07 '15 at 17:11
source share

Most likely I'll do it. Since you have the ability to modify existing defaults, define defaults, but do not use them as default arguments:

 default_name = "x" default_pass = "y" parser.add_argument( '-n', '--name', default=None, help='the login name that you wish the program to use' ) parser.add_argument( '-p', '--password', default=None, help='the password to log in with.' ) args = parser.parse_args() if all(i is not None for i in [args.name, args.password]): name = args.name passwd = args.password elif any(i is not None for i in [args.name, args.password]): parser.error("Both Name and Password are Required!") else: name = default_name passwd = default_pass 
+5
Jan 16 '13 at 2:26
source share



All Articles