sys.argv
takes arguments at the shell command line when running a program. How do I make these arguments optional?
I know I can use try
- except
. But this forces you to insert either no extra arguments or all extra arguments, unless you nest more try
- except
which makes the code look much less readable.
Suppose I would want the following functionality, how do I implement this?
$ python program.py add Peter
'Peter' was added to the list of names.
This add
argument (and not --add
) is optional such that
$ python program.py
just runs the program normally.
plac is an alternative to the standard library modules given in the other answers. It allows to define command line arguments through annotations. From the documentation, exemple 8 demonstrate optional arguments syntax :
example8.py
def main(command: ("SQL query", 'option', 'q'), dsn):
if command:
print('executing %s on %s' % (command, dsn))
# ...
if __name__ == '__main__':
import plac; plac.call(main)
Argparse exemple :
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--add", help="Add prefix to string")
args = parser.parse_args()
Note that the convention is for optional argument to be provided as "--add" while subcommands are provided as "add". There is a subcommand implementation in argparse.