Parsing command-line arguments in Python

Nothing to hand in

Goals

sys.argv

In Python, the most rudimentary way to get information from command-line arguments is by using the sys.argv list. Try running this program, for example:

import sys for index, argument in enumerate(sys.argv): print(f'{index}: /{argument}/')

Run this program with whatever arguments you want. If you save it as example.py, then try

python3 example.py python3 example.py look at these args python3 example.py args with lotsa spaces etc.

The point is that sys.argv is a list of strings starting with the name of the program file and continuing with the rest of the space-delimited arguments from the command line.

Try this sys.argv-based sample

Here's a simple sample program that uses sys.argv. Grab a copy of it and try the following:

the argparse module

If your command-line syntax is at all complicated, using sys.argv is a major pain in the neck and also error-prone. As a result, people have written many Python modules to try to simplify command-line parsing. Two such modules, argparse and getopt, are included in the standard Python library, so they're always available on any Python installation. For your upcoming assignment, you will use the argparse module to implement your command-line interface.

Here's the official argparse documentation. It's packed with feature descriptions and sample code. They've also provided a tutorial if you want it.

To get started, grab a copy of my sample argparse program.

Other choices

There are many Python modules for command-line parsing. As is usual with programming tools, each of these modules has its disciples and detractors.

I don't really love any of the choices. I think that's because command-line parsing is inherently kind of a mess, so the modules that try to make it easier are also kind of a mess. But I find argparse tolerable and better for non-trivial command interfaces than sys.argv, and I happen to like argparse better than getopt, so I use argparse for a fair number of my Python programs.

The rest of the options are third-party libraries not included in the Python standard library. (Go ahead—ask me my feelings about third-party libraries sometime.)