How to make sys.argv arguments optional?

Bentley4 picture Bentley4 · Aug 7, 2012 · Viewed 21.8k times · Source

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.

Answer

Ryan Haining picture Ryan Haining · Aug 7, 2012

EDIT to address your edit,

import sys

sys.argv = sys.argv[1:]
names = []
while sys.argv and sys.argv[0] == 'add':
    #while the list is not empty and there is a name to add
    names.append(sys.argv[1])
    print sys.argv[1], 'was added to the list of names.'
    sys.argv = sys.argv[2:]

all of the following work with this

$ python program.py add Peter
Peter was added to the list of names.

$ python program.py add Peter add Jane
Peter was added to the list of names.
Jane was added to the list of names.

$ python program.py

if the advantage to requiring 'add' before each name is that if there are any other arguments you want to look for after adding names, you can. If you want to pass multiple names by saying python program.py add Peter Jane this can be done with a fairly simple change

import sys

names = []
if len(sys.argv) > 2 and sys.argv[1] == 'add':
    names = sys.argv[2:]

for n in names:
    print n, 'was added to the list of names.'

ORIGINAL

it seems like you would be better off with something like optparse. However since sys.argv is a list you can check the length of it.

arg1 = sys.argv[1] if len(sys.argv) > 1 else 0 # replace 0 with whatever default you want
arg2 = sys.argv[2] if len(sys.argv) > 2 else 0

and then use arg1 and arg2 as your "optional" command line arguments. this will allow you to pass 1, 2, or 0 command line arguments (actually you can pass more than 2 and they will be ignored). this also assumes that the arguments have a known order, if you want to use flags like -a followed by a value, look into optparse http://docs.python.org/library/optparse.html?highlight=optparse#optparse