Read and Process Command Line Arguments in Python

How can I read and process (parse) command line arguments in Python?

In Python, how can we read the command line arguments passed to a script and process them accordingly?

I’ve worked with command-line tools for a while, and the go-to method in Python is using the argparse module, which is robust and part of the standard library. Here’s a simple example to illustrate:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

One of the reasons I stick with argparse is its features like handling multiple options in any order, supporting short and long flags, setting defaults, and even generating a help message automatically.

Adding to Vindhya’s point, if you’re looking for something simpler or need complete control, you can work directly with sys.argv. I use this approach when I want to avoid dependencies on libraries or need to process arguments in my own way. Here’s how it works:"*

import sys

print("Arguments:", sys.argv)

“The sys.argv list gives you all the arguments passed to the script. The first element (sys.argv[0]) is the script name, and the subsequent elements are the actual arguments. It’s a straightforward way to implement custom argument parsing, though you have to handle all validation and processing manually.”

Again, this is a clean way for Python read arguments when you prefer simplicity.

These are solid methods, but let me throw in another option that I’ve encountered in legacy codebases: optparse. It’s an older module that predates argparse and works similarly. However, it’s officially deprecated, so it’s not recommended for new projects. Here’s an example anyway:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet", dest="verbose", action="store_false", default=True,
                  help="don't print status messages")

(options, args) = parser.parse_args()

If you’re working on legacy Python code, you might still encounter optparse. It has similar syntax to argparse but lacks many modern features. For all new scripts, stick to argparse for compatibility and functionality.

So, Python read arguments options are varied, but always weigh your choices based on the project needs