Command-line Arguments and argparse in Python

GOAL

Today’s goal is to understand how to get command-line arguments in Python and how to use argparse module.

Environment

Windows 10
Python 3.8.7

What is command-line arguments in Python?

This is an example for parsing command-line arguments without argparse. The system can get the list of command line arguments with sys.argv.

import sys

def args_test():
    args = sys.argv
    for idx, args in enumerate(args):
        print(idx, args)

args_test()

An example of input in command prompt and the result are as below. Please note that the arguments are only string type and separated by spaces.

> python\test\argparse_test.py aa 100 "cc" [item1, items]

0 python\test\argparse_test.py
1 aa
2 100
3 cc
4 [item1,
5 items]

Optional arguments and flags

The following is an example to use optional arguments in command-line. It takes an effort to parse the list sys.argv.

import sys

def print_student_info():
    # the argument template name, age, --classes class1 class2 --absence
    # example1 Sulley 12 --classes math music science
    # example2 Mike 11 --absence --classes math
    args = sys.argv
    print("{} is {} years old".format(args[1], args[2]))

    if "--absence" in args:
        print("He/She is absent today.")

    if "--classes" in args:
        classes = []
        class_start = args.index("--classes")+1
        flag_item = list(filter(lambda x: x.startswith("--"), args[class_start:]))
        if flag_item:
            class_end = args.index(flag_item[0])
            classes = args[class_start:class_end]
        else:
            classes = args[class_start:]
        print("He/She has {} classes".format(" ".join(classes)))

print_student_info()
>python\test\argparse_test.py Sulley 12 --classes math music science
Sulley is 12 years old
class_start 4
He/She has math music science classes

>python\test\argparse_test.py Mike 11 --absence --classes math
Mike is 11 years old
He/She is absent today.
He/She has math classes

What is argparse?

The argparse is the module that makes it easy to write user-friendly command-line interfaces. It is useful when you’d like to use optional command-line arguments in your python program.

How to use argparse

You can add the argument with add_argument() function. Check the Python documentation for details about parameters for add_argument() such as “nargs” or “action”.

import sys
import argparse

def print_student_info():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", type=str)
    parser.add_argument("age", type=int)
    parser.add_argument("--classes", nargs='*') # for list of optional arguments
    parser.add_argument("--absence", action="store_true") # for optional arguments with no value

    args = parser.parse_args()

    print("{} is {} years old".format(args.name, args.age))
    if args.absence:
        print("He/She is absent today.")
    if args.classes:
        print("He/She has {} classes".format(" ".join(args.classes)))

print_student_info()
>python\test\argparse_test.py Mike 11 --classes math science --absence
Mike is 11 years old
He/She is absent today.
He/She has math science classes