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.

Subscribe

Support

Related Content

  • Davinci Resolve Proxy Files March 6, 2025

    thumbnail
  • Davinci Resolve Collaboration March 3, 2025

    thumbnail
  • Borland C Dos Programming February 27, 2025

    thumbnail
  • About Me January 3, 2025

    thumbnail
  • Support January 3, 2025

    thumbnail

Recent Content

  • MS DOS Programming the Mode X Deviation March 29, 2025

    ...
  • Mode X Madness March 22, 2025

    ...
  • Can I Program VGA Graphics in MS DOS? (Watch Me Struggle!) March 10, 2025

    ...

Archives