HOME About NCOT Documentation SineSoft Social Media Support Me

Drink tea and make things

Blog ZX Spectrum Next Computer Science Electronics Z80 Homebrew Computer Arduino and Microcontrollers

Python Commandline Argument Parsing


A quick set of notes on how to parse command line arguments properly in Python. This uses the argparse module, totally removing any effort on your part when it comes to processing command line switches.

This is for Python 3.

Here is a basic Python program that demonstrates the idea

#!/usr/bin/env python3

import argparse

helpDesc = "Compiles code into bytecode. V0.2"
argParser = argparse.ArgumentParser(description = helpDesc )

argParser.add_argument("inputfile", help="Specify input file(s).")
argParser.add_argument("--verbose", "-v", help="Enable verbose output.", action="store_true" )
argParser.add_argument("--output", "-o", help="Output filename.", default="OUT")
args = argParser.parse_args()

verbose = args.verbose
inputfile = args.inputfile
if (verbose): print ("Input file:", inputfile)

All you have to do is import the argparse module, add the arguments, parse them and then treat the whole thing as a giant dictionary of data. It’s incredibly simple and handles everything.

For more information, The Python Docs contains a lot of detail. Mostly though, the code above is all you need.

Related Content