I want this functionality:
$ python program.py add Peter
'Peter' was added to the list of names.
I can achieve this with --add
instead of add
like this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--add", help="Add a new name to the list of names",
action="store")
args = parser.parse_args()
if args.add:
print "'%s' was added to the list of names." % args.add
else:
print "Just executing the program baby."
Such that:
$ python program.py --add Peter
'Peter' was added to the list of names.
But when I change --add
to add
it is no longer optional, how can I still let it be optional yet not have those --
signs? (preferably also using the argparse
library)
What you want, is actually called "positional arguments". You can parse them like this:
Which gives you the ability to specify different actions:
You could use sub-commands to achieve this behaviour. Try something like the following
Note that the use of
nargs='*'
means thatargs.names
is now a list, unlike yourargs.add
, so you can add an arbitrary number of names followingadd
(you'll have to modify how you handle this argument). The above can then be called as follows: