Home » Programming » Python » Python Command Line Arguments

Command Line Arguments in Python Scripts, With Examples

This article will show you simple methods to pass command line arguments to your Python scripts, with some examples.

Passing arguments to your script makes it easy to build multi-use scripts that can work on different inputs. This is much easier than re-editing your code every time you want to change the inputs it will be working on.

I’ve previously covered building a full command-line application in Python, which accepts command-line options and bundles the application into a distributable package with no external dependencies – why not give it a look when you’re done here?

What are Command Line Arguments?

Command-line arguments are information passed to an application or script via the command line – it looks something like this in the terminal:

python myscript.py arg1 arg2

In the above snippet, python executes the script myscript.py, and two arguments are being passed to it – arg1 and arg2.

arg1 and arg2 may be single values or key/value pairs – but either way, the information provided to them will be used in the script – allowing a single script to be re-used with any data supplied via the arguments, rather than having to edit the script for every use.

Using getopt to Read Command Line Arguments in Python

getopt is by far the simplest method of reading and parsing command line arguments in Python scripts.

getOpt Syntax

getopt(args, shortopts, longopts=[])

Note that:

  • args is the list of arguments from the command line to be parsed
    • This is usually sys.argv[1:]
  • shortopts is a string containing the letters to use as options from the command line, separated by a colon (:)
  • longopts is an optional array of long-form options to be parsed from the command line

getOpt Example

Here’s an example Python 3 script which accepts 2 parameters. I’ll explain how it works in the comments:

# This script is written for Python 3

# Import required libraries - these should be available in a default Python 3 installation
import sys, getopt

# Get all of the arguments passed to the script
# The position of the arguments starts counting at 0
# The first will always be the name of the script
# So, we get all arguments from the first onwards (1:)
argv = sys.argv[1:]

try:
    # Retrieve the options and arguments from the argv variable using getopt.getopt()
    # The argv variable is passed to getopt() as the first parameter so that the options/arguments can be read from it, followed by the short options and the long options
    # The short options are the single letter options for your command line application, in this case -f and -b
    # The long options are the long-form name of the same variables if you want to use those instead, --foo and --bar
    # 'foo' and 'bar' are just nonsense words commonly used as placeholder variable names and values
    # You can use as many options as you want, two isn't the limit!
    options, arguments = getopt.getopt(argv, "f:b:", ["foo=","bar="])
except getopt.GetoptError:
    # There has been an error, probably as the input was not recognised - print out the arguments we expect to help the user out, then quit
    print('Invalid usage, please use the syntax: test.py -f <foo> -b <bar> or test.py --foo <foo> --bar <bar>')
    sys.exit(2)

# Loop through the options and their aguments
for opt, arg in options:
    # If the option name matches one of the 'foo' arguments, get the value for it 
    if opt in ("-f", "--foo"):
        fooValue = arg
    # Otherwise, if the option name matches one of the 'bar' arguments, get the value for it 
    elif opt in ("-b", "--bar"):
        barValue = arg
        
# The values of foo and bar, as supplied as command line arguments, are now available to use in your code
print('Foo is: ', fooValue)
print('Bar is: ', barValue)

For detailed usage of sys.argv and getopt.getopt, see the below links:

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/getopt.html

The getopt.GetoptError

This error is thrown when an unrecognized argument is found or when an argument that is required is not supplied. The exception will include the cause of the error – detailing the specific attribute which has caused the problem.

On Spaces and Special Characters

As multiple arguments are passed separated by a space, if the information you wish to pass to your script includes a space, you will need to wrap it in double quotes (“”). This preserves the meaning of all characters quoted except for $, `, \, – so that Bash variables can be used.

Similarly, if your argument contains special characters like $, `, \, , you can wrap it in single quotes (), which will preserve the meaning of all characters enclosed.

More on escaping characters on the command line in this useful StackOverflow answer.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment