目次
1. Basic Usage of Command-Line Arguments in Python
What Are Command-Line Arguments?
When running a Python program, additional information passed along with the execution command is called a “command-line argument.” This allows you to flexibly change the program’s behavior or easily provide external data. For example, by passing a filename or configuration value as an argument, you can dynamically modify the program’s behavior.Getting Command-Line Arguments with sys.argv
In Python, you can use the standard library sys
module to retrieve command-line arguments. sys.argv
is a list that stores these arguments. The first element (sys.argv[0]
) is the script name being executed, and the subsequent elements are the values passed as arguments.Sample Code: A Simple Calculation Program
import sys
def main():
if len(sys.argv) < 3:
print("Error: Two arguments are required")
return
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
print(f"Sum: {num1 + num2}")
if __name__ == "__main__":
main()
The program above takes two numbers passed from the command line, adds them, and displays the result. Example execution:$ python script.py 3 5
Sum: 8.0

2. Advanced Argument Handling with the argparse
Module
Basics of argparse
While sys.argv
allows for basic argument retrieval, when you have many arguments or need to use optional arguments and flags (such as --verbose
), the argparse
module in the standard library is more convenient. With this module, you can easily parse arguments and automatically generate error messages.Creating a Parser and Parsing Arguments
To useargparse
, first create a parser for analyzing arguments. Then, configure the parser with expected arguments and parse the actual command-line input.Sample Code: Basic Usage of argparse
import argparse
def main():
parser = argparse.ArgumentParser(description='This is a sample program')
parser.add_argument('arg1', help='The first argument')
parser.add_argument('arg2', type=float, help='The second numeric argument')
args = parser.parse_args()
print(f"arg1 = {args.arg1}")
print(f"arg2 = {args.arg2}")
if __name__ == "__main__":
main()
This program takes two arguments. arg1
is treated as a string, and arg2
as a number. After parsing, both are displayed.$ python script.py test 5.5
arg1 = test
arg2 = 5.5
Handling Optional Arguments and Flags
One of the powerful features ofargparse
is optional arguments and flags. This allows you to write code that only executes when a specific argument is provided, or to enable detailed output (such as with the --verbose
flag).Sample Code: Using Optional Arguments and Flags
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', action='store_true', help='Show detailed output')
parser.add_argument('numbers', nargs='+', type=float, help='List of numbers')
args = parser.parse_args()
total = sum(args.numbers)
if args.verbose:
print(f"Calculation details: The sum of {args.numbers} is {total}")
else:
print(f"Sum: {total}")
if __name__ == "__main__":
main()
In this program, if the --verbose
flag is provided, detailed output is displayed. Otherwise, only the simple result is shown.$ python script.py 1 2 3 --verbose
Calculation details: The sum of [1.0, 2.0, 3.0] is 6.0

3. Error Handling and Argument Validation
Validating Argument Count and Type
When working with command-line arguments, it’s important to display error messages if the user does not provide them correctly, preventing unexpected behavior. By validating argument counts and types, you can keep your program stable.Sample Code: Validating Argument Count and Type
import sys
def main():
if len(sys.argv) != 3:
print("Error: Two arguments are required")
return
try:
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
except ValueError:
print("Error: Arguments must be numeric")
return
print(f"Sum: {num1 + num2}")
if __name__ == "__main__":
main()
In this program, if the number of arguments is not exactly three (script name + two numbers), an error message is displayed. It also shows an error if the provided arguments are not numeric.4. Practical Use Cases and Applications
Example: Creating a Command-Line Tool
A practical use case for command-line arguments is creating tools that perform file operations or data processing.Sample Code: A Tool to Count File Lines
import argparse
def main():
parser = argparse.ArgumentParser(description='A tool to count lines in a file')
parser.add_argument('filename', help='The file name to count')
args = parser.parse_args()
try:
with open(args.filename, 'r') as file:
lines = file.readlines()
print(f"Number of lines in {args.filename}: {len(lines)}")
except FileNotFoundError:
print(f"Error: File {args.filename} not found")
if __name__ == "__main__":
main()
This tool counts and outputs the number of lines in the specified file.$ python count_lines.py example.txt
Number of lines in example.txt: 100
5. Conclusion
By learning how to handle command-line arguments in Python, you can make your programs more flexible. From simple methods usingsys.argv
to more complex parsing with argparse
, it’s important to choose the right approach depending on your needs. Additionally, incorporating error handling and argument validation allows you to build more robust programs.