command line arguments

READ FIRST


Remember basic_io.py? Here’s how it works in case you’ve forgotton:

$ python basic_io.py
What is your name? kevin
Go away kevin

There’s another way to pass data in to programs. We could write the program so it works like this:

$ python basic_io.py kevin
Go away kevin

In the second example, we pass kevin in as an argument on the command line. How does the program get access to kevin? Like so:

# basic_io.py
import sys
print("Go away", sys.argv[1])

The sys package contains things that are related to the system. It contains the argv variable (short for “argument vector”), which is a list of command line arguments. Create the following file, arguments.py:

# arguments.py
import sys
print(sys.argv)

Now try running the program with different command line arguments. For instance, here’s some output I got:

$ python arguments.py foo bar baz
['arguments.py', 'foo', 'bar', 'baz']
$ python arguments.py hello my name is tom marvelo riddle
['arguments.py', 'hello', 'my', 'name', 'is', 'tom', 'marvelo', 'riddle']

Notice that spaces are used to separate command line arguments. We can use quotes to include spaces inside the arguments:

$ python arguments.py hello my name is "tom marvelo riddle"
['arguments.py', 'hello', 'my', 'name', 'is', 'tom marvelo riddle']

The first element of argv is the name of the file, but we often don’t care about that. Change arguments.py so it looks like this:

# arguments.py
import sys
print(sys.argv[1:])

Now you’ll get output like this:

$ python arguments.py id like to be
['id', 'like', 'to', 'be']
$ python arguments.py under the sea
['under', 'the', 'sea']
$ python arguments.py in an octopuses garden
['in', 'an', 'octopuses', 'garden']
$ python arguments.py in the shade
['in', 'the', 'shade']

previous: case next: dictionaries