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: