How to Pass Arguments to a Python Script from the Command Line


Running Python scripts from the command line can be a great way to automate your workflows. To do this, you’ll need to learn how to pass arguments from the command line to a Python script. This will allow you to create reusable scripts that can be updated, or run for new situations or data by just passing in a couple of new arguments. In Python getting arguments from the command line to a script is quite easy.

Before you can pass arguments to a script, you’ll need to understand how to run a Python script from the command line. Follow this tutorial for a step-by-step guide.

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys (sys.argv) will store all the information in the command line entry and can be accessed inside the Python script. Python’s getopt module can also be used to parse named arguments.

Let’s go through some examples.

A Python Script to Read Command Line Arguments

To start, we’ll create a script that prints out the entire command line statement. Then we can examine how the arguments are passed and learn how to incorporate those into our code.

In the Python script, we’ll import sys, then just print out the full value of sys.argv. The script looks like this.

import sys

print('cmd entry:', sys.argv)

Save this script as myscript.py. Now we’ll call this script from the command line (follow this tutorial if you need directions), as follows. Make sure your working directory is the same directory that contains myscript.py.

You’ll notice when I call the script that I’ve included three arguments separated by a space (arg1, arg2, and arg3). These are just to illustrate how sys stores and displays the arguments. They don’t have any meaning.

Here’s my call to myscript.py from the command line. The second line of code shows the output.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py arg1 arg2 arg3
cmd entry: ['myscript.py', 'arg1', 'arg2', 'arg3']

You can see that sys.argv has stored the arguments as strings in a list. Let’s try this again with different data types (float, int, and string) to see how they are stored.

Here’s the script call and output.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py 198.3 9 arg3
cmd entry: ['myscript.py', '198.3', '9', 'arg3']

As you can see, the float and integer were also stored as strings by sys.argv.

Accessing Command Line Arguments in a Python Script

Now that we have some basic information about how to access command-line arguments and how they are stored, we can start parsing those arguments for use in our script.

In this simple example, we’ll iterate through each argument (except the first one, which is the script name) and print it to the console.

Let’s start by updating the Python script, myscript.py. We’ll add a loop to iterate through the last three arguments in sys.argv. For each element, we’ll print out its index (or position) and its value.

Here’s the new script. Notice that we iterate through a range that starts at 1. This skips the first argument, which is the script name.

import sys

for i in range(1, len(sys.argv)):
    print('argument:', i, 'value:', sys.argv[i])

Run the script using the last set of arguments. Like this.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py 198.3 9 arg3

You should get output that looks like this.

argument: 1 value: 198.3
argument: 2 value: 9
argument: 3 value: arg3

That gives you the basics of passing command-line arguments to a Python script. From here, you’ll probably want to do some logical checks to make sure the input values are the appropriate types and fall within the correct range or set of values.

Improved Parsing of Python Command Line Arguments

The examples above provide simple examples to get you started. However, if you’re looking for something more advanced that allows users to specify arguments with keywords and print help messages we’ll need to get a little more advanced.

To retrieve named arguments from the command line we’ll use Python’s getopt module. getopt is built into base Python so you don’t need to install it.

Let’s start a new script that uses both sys and getopt to parse command-line arguments. The script will have the possibility of four named arguments, ‘help’, ‘input’, ‘user’, and ‘output’. From the command line, these arguments can be specified with a single dash and the first letter (-h) or a double dash and the full argument name (--help). Name this script myscript2.py.

This script will consist of two parts. The first part is a function (myfunc) that will take the arguments (argv) as an input. The second part is an if statement that will recognize when the script is called and pass the arguments from sys.argv to myfunc.

In the body of myfunc, we’ll define variables for the input, user, and output. We’ll also define a variable for ‘help’ and give it a value. The ‘help’ variable will print out if an error is thrown or if the user specifies -h or --help.

Now call getopt.getopt and pass it the arguments from the command line, but not the script name (like this: argv[1:]). In the call to getopt is also where we specify both the parameter short and long names. The colons (:) following i, u, and o indicate that a value is required for that parameter. The equal signs (=) following input, user, and output indicate the same.

I’ve put the call to getopt.getopt into a try except statement so that the script will print the help message and then exit if there are any problems. Here’s what the script looks like so far.

import sys
import getopt


def myfunc(argv):
    arg_input = ""
    arg_output = ""
    arg_user = ""
    arg_help = "{0} -i <input> -u <user> -o <output>".format(argv[0])
    
    try:
        opts, args = getopt.getopt(argv[1:], "hi:u:o:", ["help", "input=", 
        "user=", "output="])
    except:
        print(arg_help)
        sys.exit(2)


if __name__ == "__main__":
    myfunc(sys.argv)

In the final part of the script, we’ll parse the arguments based on their short or long names, or keywords, and print out the final values.

To start, loop through all the elements of opts. This will return the argument name (opt) and value (arg). Then use an if, elif, else statement to determine which variable to assign the argument to. After all the arguments have been handled, print out the argument name and its value.

The final script should look similar to this.

import sys
import getopt


def myfunc(argv):
    arg_input = ""
    arg_output = ""
    arg_user = ""
    arg_help = "{0} -i <input> -u <user> -o <output>".format(argv[0])
    
    try:
        opts, args = getopt.getopt(argv[1:], "hi:u:o:", ["help", "input=", 
        "user=", "output="])
    except:
        print(arg_help)
        sys.exit(2)
    
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(arg_help)  # print the help message
            sys.exit(2)
        elif opt in ("-i", "--input"):
            arg_input = arg
        elif opt in ("-u", "--user"):
            arg_user = arg
        elif opt in ("-o", "--output"):
            arg_output = arg

    print('input:', arg_input)
    print('user:', arg_user)
    print('output:', arg_output)


if __name__ == "__main__":
    myfunc(sys.argv)

Let’s use this script in a couple of different ways to see what happens.

First, let’s get the help message using both the short -h and long --help names.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py -h
myscript2.py -i <input> -u <user> -o <output>
>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py --help
myscript2.py -i <input> -u <user> -o <output>

As expected, both examples resulted in the help message printing to the console.

Next, let’s see what happens if we specify an invalid argument name, --madeup.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py --madeup
myscript2.py -i <input> -u <user> -o <output>

This caused an error, which resulted in the help message printing to the console again.

Now, let’s enter the correct arguments.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py -i inputfile -u myusername -o outputfile
input: inputfile
user: myusername
output: outputfile

The arguments were assigned to the appropriate variables.

Next Steps

This article gives you a primer on passing and parsing command line arguments with Python. For a full-fledged implementation, there is still more work you will want to do. It will be important to check the types and values of the input arguments to be sure they are valid. You’ll also want to make sure to print out helpful messages to the user when an error or other exception occurs. If you’re just implementing this for personal use, those features aren’t so important. I’ve found that writing my Python scripts to run from the command line has helped me automate many of my tasks and analyses and has saved me lots of time.

Learn GIS From Industry Professionals

Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.

All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing

Konrad Hafen

Konrad is a natural resources scientist. He develops models and analysis workflows to predict and evaluate changes to landscapes and water resources.

Latest Tutorials