DEV Community

Tony Colston
Tony Colston

Posted on

how to pass command line arguments with Python

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: https://docs.python.org/3/library/sys.html

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
print(sys.argv)
Enter fullscreen mode Exit fullscreen mode

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 myprogram.py 1 a b
Enter fullscreen mode Exit fullscreen mode

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

['myprogram.py', '1', 'a', 'b']
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
chillhumanoid profile image
Jonathan Thorne

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