DEV Community


how to pass command line arguments with Python

Tony Colston
wanna be gamedev ... all around nerd and dev
・1 min read

Once you have written a few programs with Python you will want to pass arguments into those programs when your run the program (at invocation).

That is done with Python using the sys module. You will need to import that module into your program before you try to access arguments passed on the command line.

There are a LOT of other things in the sys module of use. See here for all the other stuff:

To print the arguments to your program out you will need to access a variable called sys.argv. Argv is short for argument values.

import sys

The main thing to notice is that the type of sys.argv is a list of strings. sys.argv[0] is the name of your Python script.

If you ran the Python program listed above like this:

python 1 a b

Then sys.argv0 will be the name of your Python script.

['', '1', 'a', 'b']

Notice that sys.argv is a list of strings. If your program passes a number (as I did in the example) the number will come to your Python program as a string.

Discussion (1)

chillhumanoid profile image
Jonathan Thorne

I used sys.argv at first, but I prefer click