command line arguments


Remember Here’s how it works in case you’ve forgotton:

$ python
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 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:

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,

import sys

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

$ python foo bar baz
['', 'foo', 'bar', 'baz']
$ python hello my name is tom marvelo riddle
['', '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 hello my name is "tom marvelo riddle"
['', '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 so it looks like this:

import sys

Now you’ll get output like this:

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

previous: case next: dictionaries