Using command line arguments with argv

suggest change

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.

# 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:

# 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()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Parsing Command Line Arguments:
* Using command line arguments with argv

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
57 Parsing Command Line Arguments
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve