Command-line arguments

Contents

Command-line arguments#

Python scripts can parse command-line arguments provided by the user.

argparse#

Python contains the argparse module for parsing command-line arguments.

#!/usr/bin/env python
import argparse


def say_hello(name):
    """Small CLI tool to say hello."""

    print(f"Hello {name}!")


if __name__ == "__main__":
    # Initialize the parser using the function docstring as description.
    parser = argparse.ArgumentParser(description=say_hello.__doc__)
    # Define the supported command-line arguments.
    parser.add_argument("--name", "-n", help="Your name", default="world")
    # Parse the provided command-line arguments into args.
    args = parser.parse_args()
    # Call the function with the name argument.
    say_hello(args.name)

Presuming you saved the above code as hello_cli.py, you can then provide the command-line options at runtime.

$ ./hello_cli.py
Hello world!
$ ./hello_cli.py --name Jane
Hello Jane!
$ ./hello_cli.py -n Jane
Hello Jane!
$ ./hello_cli.py --help
usage: hello_cli.py [-h] [--name NAME]

Small CLI tool to say hello.

options:
  -h, --help            show this help message and exit
  --name NAME, -n NAME  Your name

Note that the --help option was added automatically and will show the function docstring and usage options.

click#

The third-party package click provides a “Command Line Interface Creation Kit” to build advanced command-line applications. It’s syntax makes heavy use of function @decorators, which boil down to a fancy notation (also known as syntactic sugar) for function-of-a-function. This syntax allows for a terse, yet highly readable code.

#!/usr/bin/env python
import click


@click.command()
@click.option("--name", "-n", help="Your name", default="world")
def say_hello(name):
    """Small CLI tool to say hello."""

    print(f"Hello {name}!")


if __name__ == "__main__":
    say_hello()