Command-Line Interfaces

Argument Parsing

We’re going to make a command-line program that works like this:

$ python hello.py
hello world
$ python hello.py -o "custom output"
custom output
$ python hello.py -v
About to print output!
===
hello world
===
$ python hello.py -v --output="custom output"
About to print output!
===
custom output
===
$ python hello.py --help
hello - print out a message

Usage: hello.py [-hv] [-o OUTPUT]

Options:
  -o OUTPUT, --output=OUTPUT       output the given string
  -h --help                        show this help message and exit
  -v                               increase output verbosity

The meat of our program will be a function that takes a value to output and a boolean indicating whether we want to use verbose output:

def print_output(output, verbose):
    if not output:
        output = "hello world"
    if verbose:
        print("About to print output!")
        print("===")
    print(output)
    if verbose:
        print("===")

argparse

Of the few command-line parsers included with the Python standard library, argparse is the most popular.

The argparse module provides a fairly Pythonic interface for parsing command-line arguments in Python.

Here is our program implemented using argparse:

"""hello - print out a message

Usage: hello.py [-hv] [-o OUTPUT]

Options:
-o OUTPUT, --output=OUTPUT       output the given string
-h --help                        show this help message and exit
-v                               output verbose messages

"""
import argparse


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output', help="output the given string")
    parser.add_argument('-v', dest='verbose', action='store_true',
                        help="increase output verbosity")
    args = parser.parse_args()
    print_output(args.output, verbose=args.verbose)


def print_output(output, verbose):
    if not output:
        output = "hello world"
    if verbose:
        print("About to print output!")
        print("===")
    print(output)
    if verbose:
        print("===")


if __name__ == "__main__":
    main()

The argparse.ArgumentParser object is very aware of your arguments and their purposes and it automatically generates help text for you.

Notice that we’re able to train the argument parser to understand the purpose of each option.

More CLI Tools

There are a number of third-party applications that support writing command-line programs. They all work a little differently, so take a look at them and decide which one fits your needs the best.

Argparse Exercises

Tip

For all of these programs, make sure your program prints useful help information when an incorrect number of arguments or invalid arguments are specified.

Note

These exercises do not work with the automated tests.

Add

This is the add.py exercise in the modules directory. You need to create the add.py file in the modules sub-directory of the exercises directory.

Make a program add.py that takes two numbers and prints out the sum of these numbers.

$ python add.py 3 5.2
8.2
$ python add.py -7 2
-5.0
$ python add.py -2 -1
-3.0

Average

This is the average.py exercise in the modules directory. You need to create the average.py file in the modules sub-directory of the exercises directory.

Make a program average.py that calculates the average of all given command-line arguments and prints a message “No numbers to average!” if there are no arguments given.

$ python average.py 2 3 4 5 6 7
Average is 4.5
$ python average.py 2 3 4
Average is 3.0

Word Count

This is the wc.py exercise in the modules directory. You need to create the wc.py file in the modules sub-directory of the exercises directory.

Make a wc.py program that prints newline, word, and letter counts for given files. The command should take optional arguments and work in this way:

$ python wc.py --version
Word Count 1.0
$ python wc.py -h
wc - print newline, word, and letter counts for each file

Usage: wc.py [-hcwl] <file>...
wc.py (-h | --help)
wc.py --version

Options:
-c --chars    print the character count
-w --words    print the word count
-l --lines    print the newline count
-h --help     display this help and exit

The arguments should function like this:

$ python wc.py -c us-state-capitals.csv
us-state-capitals.csv:
chars 953
$ python wc.py -cl us-state-capitals.csv
us-state-capitals.csv:
lines 51
chars 953
$ python wc.py -l -c us-state-capitals.csv
us-state-capitals.csv:
lines 51
chars 953
$ python wc.py -w declaration-of-independence.txt
declaration-of-independence.txt:
words 1338
$ python wc.py declaration-of-independence.txt
declaration-of-independence.txt:
lines 67
words 1338
chars 8190
$ python wc.py -c declaration-of-independence.txt us-state-capitals.csv
declaration-of-independence.txt:
chars 8190
us-state-capitals.csv:
chars 953

Roll Die

This is the roll.py exercise in the modules directory. You need to create the roll.py file in the modules sub-directory of the exercises directory.

Create a program roll.py that simulates rolling one or more dice. The number of sides on the dice should be provided as arguments. If no arguments are given, assume a single 6 sided die.

Examples:

$ python roll.py
5
$ python roll.py 6
4
$ python roll.py 20
10
$ python roll.py 6 6
7

Convert CSV Delimiters

This is the convert_csv.py exercise in the modules directory. You need to create the convert_csv.py file in the modules sub-directory of the exercises directory.

Write a program that reads a CSV file using one delimiter format and outputs a new file using another delimiter format.

Example using the included file named people.csv that uses the | character as the delimiter, where we want it to be converted to a comma-separated file:

$ python convert_csv.py --in-delim="|" --out-delim="," people.csv people_comma.csv

Note

To run this script with escape characters (like tab) you may have to enter a tab key manually on your keyboard. You can usually do this with Ctrl-V Ctrl-TAB on Linux systems.

Difference Between

This is the difference.py exercise in the modules directory. You need to create the difference.py file in the modules sub-directory of the exercises directory.

Make a program difference.py that takes two numbers and prints the positive difference between these two numbers:

$ python difference.py 3 5
2.0
$ python difference.py 6 3.5
2.5
$ python difference.py -7 2
9.0