Issuing a usage method

A common way to help users with scripts that take command line arguments is to issue a usage message if they get it wrong, as in the following code example.

import sys

try:
    n = int(sys.argv[1])
except (IndexError, ValueError):
    sys.exit('Please enter an integer, <n>, on the command line.\nUsage: '
             'python {:s} <n>'.format(sys.argv[0]))
print(n, 'squared is', n**2)

The error message here is reported and the program exits if no command line argument was specified (and hence indexing sys.argv[1] raises an IndexError} or the command line argument string does not evaluate to an integer (in which case the int cast will raise a ValueError).

$ python eg4-usage.py hello
Please enter an integer, <n>, on the command line.
Usage: python eg4-usage.py <n>

$ python eg4-usage.py 5
5 squared is 25