How to work with command line arguments in Python?

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Mastering Command-Line Arguments in Python: A Comprehensive Guide

Working with command-line arguments is a fundamental skill for developing user-friendly and flexible Python scripts. Instead of hardcoding data into the code, developers gain the ability to pass parameters directly when running the program. In Python, the argparse module is most commonly used for these purposes. It is included in the standard library and provides powerful functionality for handling arguments.

Benefits of Using Command-Line Arguments

Using command-line arguments in Python offers developers numerous advantages:

  • Increased program flexibility by allowing changes in behavior without modifying the source code.
  • Ability to control program behavior without code changes.
  • Convenience in automating tasks and writing CLI tools.
  • Easy integration of scripts into pipelines and CI/CD processes.
  • Simplified program testing with various parameters.

Examples of Programs with Command-Line Arguments

Many popular tools actively use command-line arguments:

  • Package installers (pip, apt, yarn)
  • File manipulation tools (tar, zip, rsync)
  • Build systems (make, cmake, gradle)
  • Development tools (git, docker, kubectl)
  • Custom scripts for automating workflows

Importing and Setting Up the argparse Module

The argparse module is built into the Python standard library starting with versions 2.7 and 3.2. No additional package installation is required to use it.

import argparse

Creating a Basic Parser

To start working with arguments, you need to create an instance of the ArgumentParser class:

parser = argparse.ArgumentParser(description="Program description")

First Example of Using argparse

Consider a simple script that takes a user's name and displays a personalized greeting:

import argparse

parser = argparse.ArgumentParser(description="Simple greeting program")
parser.add_argument("name", help="User's name")
args = parser.parse_args()

print(f"Hello, {args.name}!")

The script is run as follows:

python script.py John

Execution result:

Hello, John!

Argument Types in argparse

Required Arguments

Required arguments are parameters without which the program cannot be run. They are defined without prefixes and must be passed by the user.

parser.add_argument("filename", help="File name to process")
parser.add_argument("output_dir", help="Directory to save results")

Optional Arguments

Optional arguments usually start with a single hyphen (-) for the short form or a double hyphen (--) for the long form. They provide additional program functionality.

parser.add_argument("-v", "--verbose", help="Print verbose information", action="store_true")
parser.add_argument("-o", "--output", help="File to save results")

Working with Argument Data Types

By default, all arguments are processed as strings. To specify a different data type, use the type parameter:

parser.add_argument("number", type=int, help="Enter an integer")
parser.add_argument("price", type=float, help="Product price")
parser.add_argument("enabled", type=bool, help="Enable function")

If an incorrect data type is passed, argparse will automatically issue an informative error.

Example Script for Mathematical Operations

import argparse

parser = argparse.ArgumentParser(description="Script to add two numbers")
parser.add_argument("a", type=int, help="First number")
parser.add_argument("b", type=int, help="Second number")
parser.add_argument("-o", "--operation", choices=["add", "subtract", "multiply"], 
                    default="add", help="Operation type")

args = parser.parse_args()

if args.operation == "add":
    result = args.a + args.b
elif args.operation == "subtract":
    result = args.a - args.b
elif args.operation == "multiply":
    result = args.a * args.b

print(f"Result: {result}")

Running the script:

python math_script.py 5 10 --operation multiply

Result:

Result: 50

Flags and Special Actions

Boolean Flags

To create simple on/off flags, use the action="store_true" parameter:

parser.add_argument("-v", "--verbose", action="store_true", 
                    help="Enable verbose mode")
parser.add_argument("-q", "--quiet", action="store_true", 
                    help="Quiet mode")

Counters

To count the number of flag specifications, use action="count":

parser.add_argument("-v", "--verbose", action="count", default=0,
                    help="Output detail level")

When running with -vvv, the value will be 3.

Handling Multiple Values

The nargs parameter allows you to accept multiple values with one argument:

parser.add_argument("numbers", nargs="+", type=int, 
                    help="Numbers for summation")
parser.add_argument("--files", nargs="*", 
                    help="List of files to process")

nargs value options:

  • "+" - one or more values
  • "*" - zero or more values
  • "?" - zero or one value
  • number - exact number of values

Example of Processing a List of Numbers

import argparse

parser = argparse.ArgumentParser(description="Sum calculator")
parser.add_argument("numbers", nargs="+", type=int, 
                    help="Numbers for summation")
parser.add_argument("-a", "--average", action="store_true", 
                    help="Calculate average value")

args = parser.parse_args()

total = sum(args.numbers)
print(f"Sum: {total}")

if args.average:
    average = total / len(args.numbers)
    print(f"Average: {average:.2f}")

Default Values

The default parameter allows you to set a default value for an argument:

parser.add_argument("-c", "--count", type=int, default=1, 
                    help="Number of repetitions")
parser.add_argument("--format", default="json", 
                    choices=["json", "xml", "csv"], 
                    help="Data output format")

Automatic Help

When running the script with the -h or --help parameter, help information is automatically displayed:

python script.py --help

Result:

usage: script.py [-h] name

Simple greeting program

positional arguments:
  name        User's name

optional arguments:
  -h, --help  show this help message and exit

Help Customization

You can customize various aspects of help information:

parser = argparse.ArgumentParser(
    description="Detailed program description",
    epilog="Additional information at the bottom of the help",
    formatter_class=argparse.RawDescriptionHelpFormatter
)

Creating Subcommands

The argparse module supports creating complex CLI tools with subcommands, similar to git or docker:

import argparse

parser = argparse.ArgumentParser(description="File manager")
subparsers = parser.add_subparsers(dest="command", help="Available commands")

# Copy command
copy_parser = subparsers.add_parser("copy", help="Copy files")
copy_parser.add_argument("source", help="Source file")
copy_parser.add_argument("destination", help="Destination file")

# Delete command
delete_parser = subparsers.add_parser("delete", help="Delete files")
delete_parser.add_argument("files", nargs="+", help="Files to delete")

args = parser.parse_args()

if args.command == "copy":
    print(f"Copying {args.source} to {args.destination}")
elif args.command == "delete":
    print(f"Deleting files: {', '.join(args.files)}")

Example of running:

python file_manager.py copy source.txt destination.txt

Argument Validation

Using choices

The choices parameter limits the possible values of an argument:

parser.add_argument("--level", choices=["debug", "info", "warning", "error"],
                    default="info", help="Logging level")

Custom Validation

For complex validation, you can use custom functions:

def validate_positive_int(value):
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(f"{value} is not a positive number")
    return ivalue

parser.add_argument("--timeout", type=validate_positive_int, 
                    help="Timeout in seconds")

Argument Grouping

For better help organization, you can group arguments:

parser = argparse.ArgumentParser(description="Image processing")

input_group = parser.add_argument_group("Input parameters")
input_group.add_argument("input_file", help="Input file")
input_group.add_argument("--format", help="Input file format")

output_group = parser.add_argument_group("Output parameters")
output_group.add_argument("--output", help="Output file")
output_group.add_argument("--quality", type=int, help="Compression quality")

Alternatives to argparse

The sys.argv Module

For the simplest work with arguments, you can use sys.argv:

import sys

if len(sys.argv) < 2:
    print("Usage: python script.py <name>")
    sys.exit(1)

name = sys.argv[1]
print(f"Hello, {name}!")

The click Library

Click is a powerful third-party library for creating CLI applications:

import click

@click.command()
@click.argument('name')
@click.option('--count', default=1, help='Number of greetings')
def hello(name, count):
    for _ in range(count):
        click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

The typer Library

Typer is a modern library based on type hints:

import typer

def main(name: str, count: int = 1):
    for _ in range(count):
        typer.echo(f"Hello, {name}!")

if __name__ == "__main__":
    typer.run(main)

Frequently Asked Questions

How to Handle the Situation When Arguments Are Not Passed?

Check the script's launch syntax and the correctness of argument handling in the code. Use debug printing to check values:

args = parser.parse_args()
print(f"Received arguments: {vars(args)}")

How to Handle Incorrect Data Input?

Use the type parameter and handle exceptions using try-except:

try:
    args = parser.parse_args()
except SystemExit:
    print("Error in command-line arguments")

Can I Use argparse with Jupyter Notebook?

This is technically possible but not recommended. In Jupyter Notebook, it is better to pass parameters through variables or use special magic commands.

How to Create a Required Flag?

Use the required=True parameter:

parser.add_argument("--config", required=True, 
                    help="Path to the configuration file")

How to Get All Arguments as a Dictionary?

Use the vars() function:

args = parser.parse_args()
args_dict = vars(args)
print(args_dict)

Conclusion

The argparse module provides a powerful and flexible toolkit for working with command-line arguments in Python. Mastering this module allows you to create professional CLI applications that easily integrate into various workflows and automation systems.

Studying the basic and advanced capabilities of argparse significantly improves the quality and usability of your scripts, making them more versatile and suitable for various application scenarios.

News