Reputation: 971
I am trying to have two options for the user to select..
parser = argparse.ArgumentParser(description='This is a test script...')
parser.add_argument("-test", "-t", choices='aaa,bbb,ccc,ddd'])
parser.add_argument("-dev", "-d", choices=['bbb,ddd'])
parser.add_argument("-path", "-p", choices=['Software','Hardware'])
I have a command line like this (ipy64 driver.py -t alltests -p Software)
However, args = parser.parse_args() returns args returns something like: Namespace(test='aaa', path='Software')
I want to amend this, so if -t is selected a branch of code is executed, if -d is selected a different branch of code is executed. So something like..
parser.add_argument("-dev", "-d", "-t", choices=['aaa,bbb,ccc,ddd'])
However the namespace doesn't contain a value for -test. So basically I want the user to be able to select -t or -d as one or the other options with what ever value was selected with it.
Thanks.
Upvotes: 2
Views: 2810
Reputation: 383
Would it work to make -t and -d optional? Then just test for the presence of the variable.
Set the default value to none with:
parser.add_argument("-dev", "-d", choices=['bbb,ddd', None], default =None)
Then test for a value later on:
if (parser.dev != None):
....( do code)...
I haven't tested this code, but testing for a value is how I allowed users to choose to run functions with argparse.
Upvotes: 4
Reputation: 16940
Check this out:
>>> import argparse
>>> parser = argparse.ArgumentParser(description='This is a test script...')
>>> parser.add_argument("--test", "-t", choices=['aaa','bbb','ccc','ddd'])
_StoreAction(option_strings=['--test', '-t'], dest='test', nargs=None, const=None, default=None, type=None, choices=['aaa', 'bbb', 'ccc', 'ddd'], help=None, metavar
>>> parser.add_argument("--dev", "-d", choices=['bbb','ddd'])
_StoreAction(option_strings=['--dev', '-d'], dest='dev', nargs=None, const=None, default=None, type=None, choices=['bbb', 'ddd'], help=None, metavar=None)
>>> parser.add_argument("--path", "-p", choices=['Software','Hardware'])
_StoreAction(option_strings=['--path', '-p'], dest='path', nargs=None, const=None, default=None, type=None, choices=['Software', 'Hardware'], help=None, metavar=Non
>>> args = parser.parse_args()
>>> args
Namespace(dev=None, path=None, test=None)
>>> parser.print_help()
usage: [-h] [--test {aaa,bbb,ccc,ddd}] [--dev {bbb,ddd}]
[--path {Software,Hardware}]
This is a test script...
optional arguments:
-h, --help show this help message and exit
--test {aaa,bbb,ccc,ddd}, -t {aaa,bbb,ccc,ddd}
--dev {bbb,ddd}, -d {bbb,ddd}
--path {Software,Hardware}, -p {Software,Hardware}
Upvotes: 0