Using Command Line Arguments in Python
Additional Python execution command line arguments from shells, like the command prompt in Windows or bash in Linux, can be used within a Python script. This tutorial will show you how to pass command line arguments to a Python script using sys.argv.
Let’s say the command line has the form1:
$ python script.py arg1 arg2
We can grab those arguments for use in our Python script by importing the sys module and using the sys.argv code, like this:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
So, for example, if we have the following script,
import sys
print(sys.argv[1]) # First argument indexed at 1, not 0
print(sys.argv[2])
Then we will get this result when we run our python script from the command line:
$ python script.py abc def
abc
def
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
Accessing the Python Script Name with argv
Notice how sys.argv[1]
corresponds to the first argument passed via the command line. It’s important to remember the argument indexing starts at 1, not 0. This is because the sys
module returns the input arguments to the Python interpreter call, rather than the specific script call. This means that the first argv
list element typically contains the script name. We can access the name in the following example.
Suppose we have the following script
import sys
print(sys.argv[0]) # Now indexing at 0
When executed we see the following:
$ python getName.py
getName.py
There’s a big caveat to this! Knowing that the sys.argv
list contains the inputs to the interpreter and not necessarily the script itself, any arguments passed to Python before the script name will be in sys.argv
prior to the Python script name. For example, if Python were executed with
$ python -c ....
Then sys.argv[0]
will contain the string '-c'
instead of the script name.
Hopefully this helped you learn how to incorporate command line arguments in your Python scripts. If you found it helpful, subscribe below for more free Python lessons, then share this tutorial on Facebook and Twitter.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
-
Here we are using the standard notation that “$” indicates an input line to a shell, and that the character itself is not used. ↩