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, script.py:

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

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

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 getName.py:

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.


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

  1. Here we are using the standard notation that “$” indicates an input line to a shell, and that the character itself is not used.