EDIT to refer to your editing,
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 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 over the โaddโ requirement over each name is that if there are any other arguments that you want to find after adding the 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
You seem to be better off with something like optparse. However, since sys.argv is a list, you can check its length.
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 the "optional" command line arguments. this will allow you to pass command line arguments 1, 2 or 0 (in fact, you can pass more than 2 and they will be ignored). this also assumes the arguments are in a known order, if you want to use flags like -a followed by a value, look at optparse http://docs.python.org/library/optparse.html?highlight=optparse#optparse
Ryan haining
source share