In Python application development, we often need programs to run different functions based on different parameters. For example, specifying input directories when batch processing files, or setting different processing modes in data analysis scripts. If we have to modify variables in the code every time, it's not only troublesome but also error-prone.
This article will provide a detailed introduction to several ways of reading command line arguments in Python, from the most basic sys.argv to the powerful argparse module, helping you easily implement flexible parameter configuration. Whether you're a Python beginner or a developer looking to improve code professionalism, these techniques can make your programs more practical and professional.
In actual Python development, we often encounter these scenarios:
If we hardcode these parameters in the code, we have to re-edit the code every time we make changes, which is obviously not good programming practice.
Python provides multiple methods for reading command line arguments:
sys.argv is Python's built-in parameter list that contains all arguments passed from the command line.
Basic usage:
Pythonimport sys
print("Script name:", sys.argv[0])
print("Number of arguments:", len(sys.argv))
print("All arguments:", sys.argv)
# Simple parameter processing
if len(sys.argv) > 1:
input_file = sys.argv[1]
print(f"Processing file: {input_file}")
else:
print("Please provide input filename")

argparse is a command line argument parsing module in Python's standard library, powerful and easy to use.
Basic example:
Pythonimport argparse
# Create argument parser
parser = argparse.ArgumentParser(description='File processing tool')
# Add positional argument
parser.add_argument('input_file', help='Input file path')
# Add optional arguments
parser.add_argument('-o', '--output', help='Output file path', default='output.txt')
parser.add_argument('-v', '--verbose', action='store_true', help='Show verbose information')
# Parse arguments
args = parser.parse_args()
print(f"Input file: {args.input_file}")
print(f"Output file: {args.output}")
print(f"Verbose mode: {args.verbose}")
Running example:

click is a third-party library that provides a more elegant command line interface.
Install click:
Bashpip install click
Basic usage:
Pythonimport click
@click.command()
@click.argument('input_file')
@click.option('-o', '--output', default='output.txt', help='Output file path')
@click.option('-v', '--verbose', is_flag=True, help='Show verbose information')
def process_file(input_file, output, verbose):
"""File processing tool"""
click.echo(f"Input file: {input_file}")
click.echo(f"Output file: {output}")
if verbose:
click.echo("Verbose mode enabled")
if __name__ == '__main__':
process_file()

Through learning this article, you have mastered the complete skill set for Python command line argument configuration:
sys.argv to powerful argparse, and then to elegant click, each method has its applicable scenarios.These skills not only make your Python programs more practical but also significantly improve code professionalism and user experience. In scenarios such as host computer development, data processing, and automation scripts, proficient use of these techniques will greatly enhance your work efficiency.
Remember, good command line interface design is an important hallmark of excellent Python applications. It can elevate your code from "usable" to "user-friendly"!
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!