Argument Parsing in Python

Example of command line argument parsing in Python:

import argparse

parser = argparse.ArgumentParser(description="My example script")
parser.add_argument(
        "-c", "--config-file",
        help="specify the configuration file to read (default: myscript.cfg)",
        dest="config_file",
        default="myscript.cfg")
parser.add_argument(
        "-i", "--input-file",
        help="specify the input file to read",
        required=True,
        dest="input_file")
parser.add_argument(
        "-n", "--no-modify",
        help="do not modify anything, just inform",
        action="store_true")

args = parser.parse_args()

if args.no_modify:
    print("No-modify flag set, not saving any changes")

print("Configuration file: {}".format(args.config_file))
print("Input file: {}".format(args.input_file))
# Do Stuff

Output:

$ python3 myscript.py
usage: myscript.py [-h] [-c CONFIG_FILE] -i INPUT_FILE [-n]
myscript.py: error: the following arguments are required: -i/--input-file

$ python3 myscript.py -h
usage: myscript.py [-h] [-c CONFIG_FILE] -i INPUT_FILE [-n]

My example script

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG_FILE, --config-file CONFIG_FILE
                        specify the configuration file to read (default:
                        myscript.cfg)
  -i INPUT_FILE, --input-file INPUT_FILE
                        specify the input file to read
  -n, --no-modify       do not modify anything, just inform

$ python3 myscript.py -i filename.txt
Configuration file: myscript.cfg
Input file: filename.txt

$ python3 myscript.py -i filename.txt -n
No-modify flag set, not saving any changes
Configuration file: myscript.cfg
Input file: filename.txt

$ python3 myscript.py -i filename.txt -n -c special_set_of_configs.cfg
No-modify flag set, not saving any changes
Configuration file: special_set_of_configs.cfg
Input file: filename.txt

More information: https://docs.python.org/3/library/argparse.html

Also available in GitHub: https://github.com/markkuleinio/python-argument-parsing

Updated: April 22, 2019 — 16:54

1 Comment

Add a Comment
  1. Thank you! Exactly what I needed.

Leave a Reply