Python Language Using command line arguments with argv


Whenever a Python script is invoked from the command line, the user may supply additional command line arguments which will be passed on to the script. These arguments will be available to the programmer from the system variable sys.argv ("argv" is a traditional name used in most programming languages, and it means "argument vector").

By convention, the first element in the sys.argv list is the name of the Python script itself, while the rest of the elements are the tokens passed by the user when invoking the script.

import sys

$ python
=> ['']

$ python fizz
=> ['', 'fizz']

$ python fizz buzz
=> ['', 'fizz', 'buzz']

Here's another example of how to use argv. We first strip off the initial element of sys.argv because it contains the script's name. Then we combine the rest of the arguments into a single sentence, and finally print that sentence prepending the name of the currently logged-in user (so that it emulates a chat program).

import getpass
import sys

words = sys.argv[1:]
sentence = " ".join(words)
print("[%s] %s" % (getpass.getuser(), sentence))

The algorithm commonly used when "manually" parsing a number of non-positional arguments is to iterate over the sys.argv list. One way is to go over the list and pop each element of it:

# reverse and copy sys.argv
argv = reversed(sys.argv)
# extract the first element
arg = argv.pop()
# stop iterating when there's no more args to pop()
while len(argv) > 0:
    if arg in ('-f', '--foo'):
        print('seen foo!')
    elif arg in ('-b', '--bar'):
        print('seen bar!')
    elif arg in ('-a', '--with-arg'):
        arg = arg.pop()
        print('seen value: {}'.format(arg))
    # get the next value
    arg = argv.pop()