Using command line arguments with argv
suggest changeWhenever 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 in the list 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 script path as it was invoked, while the rest of the elements are the tokens passed by the user when invoking the script.
# cli.py
import sys
print(sys.argv)
$ python cli.py
['cli.py']
$ python cli.py fizz
['cli.py', 'fizz']
$ python cli.py fizz buzz
['cli.py', '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:
import sys
# Copy the user arguments. reversed() is an iterator and has no pop().
argv = list(reversed(sys.argv[1:]))
while argv:
arg = argv.pop()
if arg in ('-f', '--foo'):
print('seen foo!')
elif arg in ('-b', '--bar'):
print('seen bar!')
elif arg in ('-a', '--with-arg'):
arg = argv.pop()
print('seen value: {}'.format(arg))
argv.pop() raises IndexError when --with-arg has no following value. Popping once before the loop and again at the bottom skips the last token; this loop pops at the start of each pass instead.