Python Command Line Arguments - How to Pass and Read Arguments in Python Scripts

When you run a Python script from the terminal, you can pass arguments after the script name. These arguments are captured inside Python using the sys.argv list.

This mechanism is part of Python’s command-line interface (CLI) support.

1. Basic Idea

When you run a command like this:

Bash

python script.py arg1 arg2 arg3    

Python internally creates a list called sys.argv.

Python

sys.argv = ["script.py", "arg1", "arg2", "arg3"]    

Important points:

So, Python simply stores command-line arguments in a list.

Example: Print All Arguments

Create a Python file named example.py.

Python

# Import the sys module to access command-line arguments
import sys

# Print the entire argument list
print("All arguments:", sys.argv)

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

# Check if additional arguments exist
if len(sys.argv) > 1:
    print("First argument:", sys.argv[1])

if len(sys.argv) > 2:
    print("Second argument:", sys.argv[2])    

Run the script using the following command:

Bash

python example.py apple mango banana    

The output of the above code is:

Output

All arguments: ['example.py', 'apple', 'mango', 'banana']
Script name: example.py
First argument: apple
Second argument: mango    

Example: Adding Numbers from CLI

This example demonstrates a practical use case.

Create a Python file named add_numbers.py.

Python

import sys

# sys.argv contains command-line arguments
# Example execution:
# python add_numbers.py 10 20

# Convert arguments to integers
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

# Perform addition
result = num1 + num2

# Print result
print("Sum:", result)    

Run the script in the terminal:

Bash

python add_numbers.py 10 20    

The output of the above code is:

Output

Sum: 30    

Example: Loop Through Arguments

Sometimes you want to process multiple inputs dynamically.

Python

import sys

# Skip index 0 because it contains script name
for arg in sys.argv[1:]:
    print("Argument:", arg)    

Run:

Bash

python script.py A B C D    

The output of the above code is:

Output

Argument: A
Argument: B
Argument: C
Argument: D    

Real Example (Useful for Data / ML Scripts)

Suppose you want to pass a dataset file name dynamically.

Create a Python file named train_model.py.

Python

import sys
import pandas as pd

# Get dataset filename from CLI
dataset_file = sys.argv[1]

# Load dataset
df = pd.read_csv(dataset_file)

print("Dataset loaded successfully")
print("Shape:", df.shape)    

Run the script:

Bash

python train_model.py sales.csv    

The output of the above code is:

Output

Dataset loaded successfully
Shape: (5000, 8)    

This technique is commonly used in: