Parsing command-line arguments in Python

Nothing to hand in, but you're going to want to know this stuff.

Goals

Update your copy of my samples repository

If you don't have it yet:

git clone https://github.com/ondich/cs257-2025-spring.git

If you do have it already:

cd cs257-2025-spring git pull

Once you have gotten an updated clone of my repo, make sure it has a folder named arguments with two python programs in it.

Simple CLI processing using sys.argv

In Python, the most rudimentary way to get information from command-line arguments is by using the sys.argv list.

To get a feel for this, try creating a file named example.py and put this code in it:

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

Try running this program with whatever arguments you want. For example:

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

In my repository, there's a simple sample program called sysargv-sample.py that uses sys.argv. In your clone of my repo, cd to arguments and try the following:

CLI processing with argparse

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, look in my repo's arguments directory for this sample argparse program called argparse-sample.py.

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.)