How To Pass Command-Line Values to a Python Script

Use argparse to define script values

Jonathan Hsu
Code 85

--

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…

--

--