How to make sys.argv arguments optional?

Viewed 27904

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.

Edit

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.

4 Answers

As a simple answer to your question, you can have an optional argument with sys.argv, but if you foresee your module expanding much you may want to consider another module like argparse as suggested elsewhere.

This will ignore no args, but allow an arbitrary number of args after that.

#!/usr/bin/env python

import sys

added = sys.argv[1:]
if added:
    for add in added:
        print("{0} was added to the list of names.".format(add))
$ ./test.py
$ ./test.py Peter
Peter was added to the list of names.

Of course you are not passing add Peter just Peter. But if that is acceptable, then this works.

My point is you can certainly do optional args with sys, and in fact for very simple scripts it is often not necessary to use argparse if that suffices!

Related