Sunday, January 12, 2025
HomeComputer ScienceCommand Line Arguments in Python

Command Line Arguments in Python

In Python, command-line arguments allow you to pass information to a Python script when running it from the command line or terminal. This is useful for making your script more dynamic and customizable without modifying the script itself.

Accessing Command-Line Arguments in Python:

Python provides the sys module to handle command-line arguments. Specifically, the sys.argv list holds the arguments passed to the script.

Syntax:

python
import sys

# sys.argv is a list where:
# sys.argv[0] is the script name
# sys.argv[1:] are the arguments passed to the script

Steps to Use Command-Line Arguments:

  1. Import the sys Module: You need to import sys to access sys.argv.
  2. Run the Script with Arguments: When you run a Python script from the command line, you can pass additional arguments after the script name.

Example 1: Basic Example of Command-Line Arguments

Python Script (example.py):

python
import sys

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

# Print the arguments passed to the script
print("Arguments passed:", sys.argv[1:])

How to run the script:

bash
python example.py arg1 arg2 arg3

Output:

less
Script name: example.py
Arguments passed: ['arg1', 'arg2', 'arg3']

In this example, sys.argv contains a list where:

  • sys.argv[0] is the name of the script (example.py),
  • sys.argv[1:] contains the arguments passed after the script name (arg1, arg2, arg3).

Example 2: Using Command-Line Arguments in a Program

Here’s an example where we pass two numbers to the script and calculate their sum.

Python Script (sum.py):

python
import sys

# Check if enough arguments are provided
if len(sys.argv) != 3:
print("Usage: python sum.py <num1> <num2>")
sys.exit(1)

# Get the two numbers from command-line arguments
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])

# Calculate the sum
sum_result = num1 + num2

# Print the result
print(f"The sum of {num1} and {num2} is {sum_result}")

How to run the script:

bash
python sum.py 5 7

Output:

python
The sum of 5.0 and 7.0 is 12.0

In this example:

  • We use sys.argv[1] and sys.argv[2] to fetch the two command-line arguments.
  • The script converts them to float to handle decimal numbers and calculates their sum.

Example 3: Using argparse Module for Advanced Argument Parsing

For more complex command-line parsing (e.g., flags, optional arguments), you can use the argparse module. This module provides a more structured way to handle arguments and automatically generates help messages.

Python Script (example_argparse.py):

python
import argparse

# Create the parser
parser = argparse.ArgumentParser(description="Sum two numbers.")

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

# Parse the arguments
args = parser.parse_args()

# Calculate the sum
sum_result = args.num1 + args.num2

# Print the result
print(f"The sum of {args.num1} and {args.num2} is {sum_result}")

How to run the script:

bash
python example_argparse.py 5 7

Output:

python
The sum of 5.0 and 7.0 is 12.0

With argparse, you can also add optional arguments, set default values, and automatically generate usage help.

Key Features of argparse:

  • Positional arguments: Arguments that are required and are passed in a specific order.
  • Optional arguments: Arguments that are optional, typically with flags (e.g., -v or --verbose).
  • Help messages: Automatically generated help and usage documentation.

For example:

bash
python example_argparse.py -h

This will display the automatically generated help message:

sql
usage: example_argparse.py [-h] num1 num2

Sum two numbers.

positional arguments:
num1 First number
num2 Second number

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

Summary:

  • sys.argv: A simple way to access command-line arguments as a list.
  • argparse: A powerful module for advanced command-line argument parsing, with features like help messages, optional arguments, and default values.

Using command-line arguments in Python makes your scripts more flexible and allows users to customize them without editing the code itself.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

HTML Form

What are some funny memes?

Top 10 Smartwatches

Recent Comments

0
Would love your thoughts, please comment.x
()
x