How To Pass Command-Line Values to a Python Script

Use argparse to define script values

How To Pass Command-Line Values to a Python Script
Photo by Cupcake Media on Unsplash

Python provides a native library for passing command-line values to scripts called argparse. With argparse, we can include variable values in the execution command instead of using input() to request the value mid-execution. This saves us time and more importantly allows script execution lines to be saved and conveniently used — either manually or automated.

If you’ve written any Python scripts that require one or two values via input(), then read on and consider implementing argparse to simplify the execution of your scripts. I’ve implemented argparse in scripts such as my command-line JSON splitter and many of the iFormBuilder API tools.

In this guide, we’ll introduce the argparse library, how to begin using it, and some tips and tricks to avoid common pitfalls as you get on your way.

What is argparse?

Python has a variety of native libraries, available by a simple import. Argparse — short for argument parser — is a library that allows us to define command-line arguments.

These arguments can be either required or optional. Additionally, we can define the data type and helper text for each argument. If your script has an argument that is needed for the script to function properly, then the argument should be required. If the value is optional or will have a default value within the script, then the argument can be optional.

Our First argparse Script

Let’s get started writing our first argsparse script. We begin with an import statement and creating an ArgumentParser() object.import argparseparser = argparse.ArgumentParser()

Our ArgumentParser object — stored in the variable parser — will be used to define our command-line arguments. We’ll start by using the .add_argument() method to define an argument for a number. Afterwards, use the .parse_args() method to store our data to a variable. Finally, we’ll print our argument value to demonstrate how it is referenced.import argparseparser = argparse.ArgumentParser()
parser.add_argument("number")args = parser.parse_args()
print(args.number * 2)

To see how the script works, open up your terminal and execute the script as normal. You should receive an error. This is because our argument was not included in the script call.> python3 app.pyusage: app.py [-h] number
app.py: error: the following arguments are required: number

This time, we’ll pass a value to the script by entering it directly after the file’s name.> python3 app.py 5
55

The good news is, we did not receive an error; however, our output is not what was expected. This is because an argument from argparse is going to be defined as a string… unless we tell it otherwise.

Let’s add a data type definition to our argument.import argparseparser = argparse.ArgumentParser()
parser.add_argument("number", type=int)args = parser.parse_args()
print(args.number * 2)

Now when we execute, we have the value of number properly doubled.> python3 app.py 5
10

What if we want to add an optional argument? To do this, we must prefix the argument’s name with a hyphen. Additionally, we must add a dest attribute to our argument, which specifies the name in which the value will be stored.import argparseparser = argparse.ArgumentParser()
parser.add_argument("num1", type=int)
parser.add_argument("--num2", type=int, dest="num2")args = parser.parse_args()if args.num2:
  print(args.num1 * args.num2)
else:
  print(args.num1 * 2)

To pass a value to an optional argument, the name must be used in the script execution command.> python3 app.py 5 --num2 5
25> python3 app.py 5
10

Tips and Tricks

After covering the basics of argparse, you’re ready to go out into the world and write scripts which require command-line arguments! But there are plenty of opportunities for roadblocks and opportunities that are not fully realized. To prepare you for success, here are three tips and tricks that go beyond the simple basics.

Optional arguments do not need to have command-line value

If you want to use an optional argument as a simple flag, then set the action="store_true" attribute in your argument definition. With this in place, including the argument in the execution command will result in a value of True being stored.

Let’s change up our arguments to be a more realistic example.import argparseparser = argparse.ArgumentParser()
parser.add_argument("greeting")
parser.add_argument("--caps", action="store_true")args = parser.parse_args()if args.caps:
  print(args.greeting.upper())
else:
  print(args.greeting)

Now take a look at the differences in script execution commands.> python3 app.py "Hello World"
Hello World> python3 app.py "Hello World" --caps
HELLO WORLD

I often use a --debug argument in my scripts to determine if I’d like extra logging during the execution.

Include helper text

Variables always make perfect sense when we create them, but what about in one week? one month? what about when you share your script with a colleague? The bottom line is that a little bit of documentation can go a long way and avoid traversing through your code as a refresher.

Fortunately, argparse has the ability to define helper text with our arguments. Inside the .add_argument() method, we can pass a keyword argument help with a string value.import argparse
parser = argparse.ArgumentParser()parser.add_argument("greeting", help="Text to be printed")
parser.add_argument("--caps", help="capitalize the greeting", action="store_true")

Now, our helper text is displayed we use --help from the command-line.> python3 app.py --help
usage: app.py [-h] [--caps] greetingpositional arguments:
 greeting    Text to be printedoptional arguments:
 -h, --help  show this help message and exit
 --caps      capitalize the greeting

Using --help is a universal technique to argparse so expect that user will know leverage the help menu. I often use help text to communicate string formats and data types for arguments such as date formats or that an argument must be an integer.

Set a short version of argument names

Generally speaking, the practice of using excessively short names is frowned upon. The convenience is often outweighed by possible confusion and lack of context. That being said, there’s no denying the potential convenience.

We can define multiple names for an argument, which gives us the best of both worlds.import argparseparser = argparse.ArgumentParser()parser.add_argument("greeting", help="Text to be printed")
parser.add_argument("-c", "--caps", action="store_true")

Now, we can use both -caps as well as -c for our optional argument. Use this technique when your argument(s) are easily identified by their first letter.


Hope you enjoyed the article. Please share your experiences, questions, and feedback below.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe