How to Handle Python Command Line Arguments

I have found that hardcoding values is the quickest way to make a script useless. I remember building a data scraper for a real estate firm in Chicago, where the city name was buried deep in the code.

Every time they wanted to switch from Chicago to Houston, I had to manually edit the script. It was a nightmare.

That is when I truly mastered command line arguments, and it changed how I write code forever.

Use Command Line Arguments

Command-line arguments allow you to pass information into your script at the moment of execution.

This makes your tools reusable, professional, and easy to integrate into larger automated pipelines.

In this tutorial, I will walk you through the three most effective ways I handle these arguments in my daily work.

Method 1: The Quick and Dirty sys.argv

When I need to whip up a small script for a one-off task, I usually reach for the sys.argv module.

It is a simple list that contains all the strings you typed into the terminal to run your program.

In the example below, I’ve written a script that helps a logistics manager calculate the total shipping weight for a delivery in New York.

import sys

# The first element sys.argv[0] is always the script name
# We start from index 1 to get the actual data
def calculate_shipping():
    if len(sys.argv) < 3:
        print("Error: Please provide the State and Total Weight.")
        print("Usage: python shipping.py [State] [Weight]")
        return

    destination_state = sys.argv[1]
    package_weight = sys.argv[2]

    print(f"Processing shipment to: {destination_state}")
    print(f"Total package weight recorded: {package_weight} lbs")

if __name__ == "__main__":
    calculate_shipping()

I executed the above example code and added the screenshot below.

Handle Python Command Line Arguments

To run this in your terminal, you would type: python shipping.py NY 45

I like this method because it requires zero configuration, but be careful, it doesn’t handle data types or help messages for you.

Method 2: The Professional Way with argparse

For any production-level tool I build, argparse is my go-to library in the Python Standard Library.

It automatically generates a help menu (the –help flag) and handles data type conversion on the fly.

Imagine you are building a tool for a financial analyst on Wall Street to calculate quarterly tax estimates.

import argparse

def calculate_tax():
    # Initialize the parser with a helpful description
    parser = argparse.ArgumentParser(description="Wall Street Quarterly Tax Calculator")

    # Add arguments with specific types and help text
    parser.add_argument("revenue", type=float, help="Total quarterly revenue in USD")
    parser.add_argument("--rate", type=float, default=0.21, help="Tax rate (default is 0.21 for 21%)")
    parser.add_argument("--state", choices=["NY", "NJ", "CT"], default="NY", help="Tri-state area code")

    args = parser.parse_args()

    tax_amount = args.revenue * args.rate
    print(f"Summary for {args.state}:")
    print(f"Quarterly Revenue: ${args.revenue:,.2f}")
    print(f"Estimated Tax: ${tax_amount:,.2f}")

if __name__ == "__main__":
    calculate_tax()

I executed the above example code and added the screenshot below.

How to Handle Python Command Line Arguments

When you run python tax_calc.py 50000 –rate 0.25 –state NJ, the script knows exactly what to do.

I find the choices parameter incredibly useful for preventing users from entering invalid data.

Method 3: Handle Flags and Booleans

Sometimes you just need a “switch” to turn a feature on or off, like a “Dry Run” mode for a database migration.

I use the action=”store_true” parameter in argparse to handle these boolean flags efficiently.

Here is an example for a script that processes California voter registration data.

import argparse

def process_voters():
    parser = argparse.ArgumentParser(description="CA Voter Data Processor")
    
    parser.add_argument("file", help="Path to the CSV file")
    parser.add_argument("--verbose", action="store_true", help="Show detailed processing logs")
    parser.add_argument("--dry-run", action="store_true", help="Verify data without saving to DB")

    args = parser.parse_args()

    print(f"Reading file: {args.file}")
    
    if args.dry_run:
        print("[MODE] Running in Dry Run mode. No changes will be saved.")
    
    if args.verbose:
        print("[LOG] Connecting to Sacramento data server...")
        print("[LOG] Validating ZIP codes...")

if __name__ == "__main__":
    process_voters()

I executed the above example code and added the screenshot below.

Handle Command Line Arguments in Python

I’ve used this “Dry Run” pattern hundreds of times to prevent accidental data loss in live environments.

Which Method Should You Choose?

In my experience, if your script has more than two inputs, skip sys.argv and go straight to argparse.

While sys.argv is faster to type, the time you save is usually lost later when you forget the order of the arguments.

Using argparse makes your code self-documenting, which your future self will definitely appreciate.

I hope you found this tutorial helpful! Handling command-line arguments is a fundamental skill that separates hobbyist scripts from professional software.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.