
Command Line Arguments in Python
Command line arguments are values passed to a program when it is executed from the command line or terminal. They provide a way to customize the behavior of a program without modifying its source code.
In Python, you can access command line arguments using the sys.argv list provided by the sys module. Each command line argument passed to the program is stored as a string in the sys.argv list.
# Access command line arguments
arguments = sys.argv
# Print command line arguments
print("Command Line Arguments:", arguments)
You can access specific command line arguments by indexing into the sys.argv list. Remember that the first element (sys.argv[0]) contains the name of the script itself, and subsequent elements contain the actual arguments.
# Access specific command line arguments
script_name = sys.argv[0]
first_argument = sys.argv[1]
second_argument = sys.argv[2]
# Print specific command line arguments
print("Script Name:", script_name)
print("First Argument:", first_argument)
print("Second Argument:", second_argument)
To parse command line arguments more conveniently, you can use libraries like argparse or optparse. These libraries provide a structured way to define and handle command line options and arguments.
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='Process some integers.')
# Add arguments
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
# Parse command line arguments
args = parser.parse_args()
# Print the result
print(args.accumulate(args.integers))
1. Calculator Application:
You are developing a command-line calculator application that performs basic
arithmetic operations (addition, subtraction, multiplication, division) on
two numbers provided as command-line arguments.
# Check if correct number of arguments are provided
if len(sys.argv) != 4:
print("Usage: python calculator.py
sys.exit(1)
num1 = float(sys.argv[1])
operation = sys.argv[2]
num2 = float(sys.argv[3])
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 == 0:
print("Error: Division by zero")
sys.exit(1)
result = num1 / num2
else:
print("Error: Invalid operation")
sys.exit(1)
print("Result:", result)
2. File Converter:
You want to create a command-line utility to convert text files from one
format to another (e.g., from CSV to JSON). The input file and desired
output format will be provided as command-line arguments.
import csv
import json
# Check if correct number of arguments are provided
if len(sys.argv) != 4:
print("Usage: python converter.py input_file output_file format")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
output_format = sys.argv[3]
if output_format not in ['csv', 'json']:
print("Error: Invalid output format")
sys.exit(1)
if output_format == 'csv':
# Convert JSON to CSV
with open(input_file, 'r') as f:
data = json.load(f)
with open(output_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(data[0].keys()) # Write header
for row in data:
writer.writerow(row.values())
elif output_format == 'json':
# Convert CSV to JSON
with open(input_file, 'r') as f:
reader = csv.DictReader(f)
data = [row for row in reader]
with open(output_file, 'w') as f:
json.dump(data, f, indent=4)
3. Password Generator:
You want to create a command-line tool to generate random passwords of
specified length. The desired length of the password will be provided as a
command-line argument.
import random
import string
# Check if correct number of arguments are provided
if len(sys.argv) != 2:
print("Usage: python password_generator.py < length>")
sys.exit(1)
length = int(sys.argv[1])
password = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
print("Generated Password:", password)
4. Data Analysis Tool:
You are developing a command-line tool for basic data analysis tasks such as
calculating the mean, median, and mode of a dataset provided as a
command-line argument.
import statistics
# Check if correct number of arguments are provided
if len(sys.argv) < 2:
print("Usage: python data_analysis.py
sys.exit(1)
data = [float(arg) for arg in sys.argv[1:]]
mean = statistics.mean(data)
median = statistics.median(data)
mode = statistics.mode(data)
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
Command line arguments provide a way to pass inputs to a Python program from the command line or terminal. By accessing the sys.argv list or using libraries like argparse or optparse, you can easily handle and parse command line arguments in your Python programs. This allows for greater flexibility and customization when running Python scripts from the command line.