September 11, 2024

Python Command line arguments

Command-line arguments are parameters passed to a Python script at the time of execution. They allow you to provide input to the script directly from the command line, making your scripts more dynamic and flexible. In Python, command-line arguments are accessed using the sys.argv list from the sys module.

1. Accessing Command Line Arguments

The sys.argv list contains the command-line arguments passed to the script. The first element, sys.argv[0], is the name of the script, and the subsequent elements are the arguments.

import sys

# Print the script name
print("Script name:", sys.argv[0])

# Print the command-line arguments
print("Arguments:", sys.argv[1:])

For example, if you run the script as python script.py arg1 arg2 arg3, the output will be:

Script name: script.py
Arguments: ['arg1', 'arg2', 'arg3']

2. Counting Command Line Arguments

You can use len(sys.argv) to get the number of command-line arguments passed to the script (including the script name).

import sys

# Count the number of arguments
num_args = len(sys.argv)

print("Number of arguments:", num_args)

3. Handling Command Line Arguments

To handle command-line arguments effectively, you can parse and process them according to your needs. Here is an example where the script expects two arguments for a simple addition operation:

import sys

# Check if the correct number of arguments is provided
if len(sys.argv) != 3:
    print("Usage: python script.py  ")
    sys.exit(1)

# Get the arguments
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])

# Perform the addition
result = num1 + num2

print("Result:", result)

If you run this script as python script.py 5 10, the output will be:

Result: 15.0

4. Using argparse for Advanced Argument Parsing

For more complex command-line argument handling, Python provides the argparse module. This module allows you to define arguments, options, and their types, as well as automatically generate help messages.

4.1. Basic Example of argparse

Here’s a simple example of using argparse to handle command-line arguments:

import argparse

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

# Add arguments
parser.add_argument('num1', type=int, help='First number')
parser.add_argument('num2', type=int, help='Second number')

# Parse the arguments
args = parser.parse_args()

# Perform the addition
result = args.num1 + args.num2

print("Result:", result)

If you run this script as python script.py 5 10, the output will be:

Result: 15

4.2. Adding Optional Arguments

You can also add optional arguments (flags) using argparse:

import argparse

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

# Add arguments
parser.add_argument('num1', type=int, help='First number')
parser.add_argument('num2', type=int, help='Second number')
parser.add_argument('--operation', choices=['add', 'subtract'], default='add', help='Operation to perform')

# Parse the arguments
args = parser.parse_args()

# Perform the specified operation
if args.operation == 'add':
    result = args.num1 + args.num2
elif args.operation == 'subtract':
    result = args.num1 - args.num2

print("Result:", result)

Now you can specify the operation using the --operation flag. For example:

python script.py 5 10 --operation add
# Output: Result: 15

python script.py 5 10 --operation subtract
# Output: Result: -5

5. Generating Help Messages

The argparse module automatically generates help messages based on the arguments you define. You can view the help message by running the script with the --help flag:

python script.py --help

This will display a help message showing the usage of the script, the arguments, and their descriptions.

Command-line arguments allow you to pass input to your Python scripts directly from the command line, making your scripts more dynamic and flexible. For basic argument handling, the sys.argv list is sufficient. However, for more complex scenarios, the argparse module provides a powerful and flexible way to define, parse, and manage command-line arguments.