Python Command Line Arguments

Command-line arguments in Python are inputs sent to a Python script at the time of execution through the command-line interface (CLI). Such arguments can be used to control the behavior of the script when it is run, all without a change in its source code.

Here’s a detailed explanation:

How Command Line Arguments Work

When you run the Python script from the command line, you can add arguments following the script name. They are passed to the script as strings and can be processed inside the script.

Basic Syntax

python script.py arg1 arg2 arg3
  • script.py: The Python file to run.
  • arg1, arg2, arg3: Command line arguments provided to the script.

Accessing Command Line Arguments

The arguments are captured through a special list called sys.argv, which is available in the module sys.

Structure of sys.argv

  1. sys.argv[0]: The script name (or the full path to the script).
  2. sys.argv[1:]: The list of additional arguments passed to the script.

Example 1: Basic Argument Parsing

import sys

# Print all command line arguments
print("Arguments passed:", sys.argv)

# Access individual arguments
script_name = sys.argv[0]
if len(sys.argv) > 1:
    first_arg = sys.argv[1]
else:
    first_arg = None

print("Script name:", script_name)
print("First argument:", first_arg)

Run in CLI:

python example.py hello world

Output:

Arguments passed: ['example.py', 'hello', 'world']
Script name: example.py
First argument: hello

Using argparse for Advanced Parsing

The argparse module is generally used for more robust handling of arguments. It allows you to define expected arguments, their types, default values, and more.

Example 2: Using argparse

import argparse

# Create the parser
parser = argparse.ArgumentParser(description="Process some integers.")

# Add arguments
parser.add_argument('integers', type=int, nargs='+', help='An integer to process')
parser.add_argument('--sum', action='store_true', help='Sum the integers')

# Parse the arguments
args = parser.parse_args()

# Use the arguments
if args.sum:
    print("Sum of integers:", sum(args.integers))
else:
    print("Integers:", args.integers)

Run in CLI:

python example.py 1 2 3 --sum

Output:

Sum of integers: 6

Key Features of argparse

  • Positional Arguments: Mandatory arguments that appear in the order.
  • Optional Arguments: Arguments prefixed with -- or -, often used as flags or with specific values.
  • Default Values: Set default values for arguments if not provided.
  • Help Messages: Automatically generated usage messages and descriptions.

Advanced Libraries for Command Line Arguments

  1. click: Simplifies command-line interface creation.
  • Example:
import click

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

if __name__ == '__main__':
    greet()

2. typer: A modern alternative based on type annotations.

  • Example:
import typer

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

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

Common Use Cases

  1. Automation Scripts: Pass file paths, configurations, or options to scripts.
  2. Data Processing: Specify input/output files and processing parameters.
  3. Testing and Debugging: Enable different modes or levels of verbosity.

Tips

  1. Always Validate Input: Validate types and values of arguments for error-free execution.
  2. Use argparse for Complex Scripts: It is very clear and gives better user experience with automatically generated help.
  3. Test command-line interfaces: Run multiple test cases to ensure that arguments are parsed correctly.