涨薪技术|Python命令行参数化的四种方式

发布时间:2026/7/20 21:36:23
涨薪技术|Python命令行参数化的四种方式 Python命令行参数化是在脚本调用时通过命令行向脚本传递参数的一种方式。下面介绍Python命令行参数化的四种方式及其使用方法。1使用sys模块Python中的sys模块提供了一个名为argv的列表该列表以字符串形式包含了命令行参数。通过该列表我们可以轻松地对命令行参数进行处理。下面是一个使用sys模块的例子。import sys if __name__ __main__: args sys.argv print(args)上面的代码使用sys.argv获取命令行参数并打印出了获取到的参数示例输出如下​​​​​​​$ python example.py 1 2 3 [example.py, 1, 2, 3]在上述输出中列表中的第一项是脚本名称其余项为命令行参数。2使用getopt模块getopt模块提供了一种更加灵活的方式来解析命令行参数。getopt模块提供了getopt和getopt_long两种方法。这两种方法都支持Unix style和GNU style的命令行参数格式。下面是一个使用getopt模块的例子。​​​​​​​import getopt import sys if __name__ __main__: opts, args getopt.getopt(sys.argv[1:], hi:o:, [input, output]) input_file, output_file None, None for opt, arg in opts: if opt -h: print(getopt example.py -i inputfile -o outputfile) sys.exit() elif opt in (-i, --input): input_file arg elif opt in (-o, --output): output_file arg print(finput file: {input_file}) print(foutput file: {output_file})上面的代码使用getopt模块获取命令行参数并打印出了获取到的参数。示例输出如下​​​​​​​$ python example.py -i input.txt -o output.txt input file: input.txt output file: output.txt在上述输出中程序正确解析了-i和-o参数并分别对应了input_file和output_file变量。3使用argparse模块argparse模块是Python标准库中用于解析命令行参数的模块。argparse模块提供了比getopt模块更加优雅、易用的API可以快速编写出高质量的命令行工具。下面是一个使用argparse模块的例子。​​​​​​​import argparse if __name__ __main__: parser argparse.ArgumentParser(descriptionargparse example) parser.add_argument(-i, --input, helpinput file name) parser.add_argument(-o, --output, helpoutput file name) args parser.parse_args() print(finput file: {args.input}) print(foutput file: {args.output})上面的代码使用argparse模块获取命令行参数并打印出了获取到的参数。示例输出如下​​​​​​​$ python example.py -i input.txt -o output.txt input file: input.txt output file: output.txt在上述输出中程序正确解析了-i和-o参数并分别对应了args.input和args.output变量。argparse模块还提供了许多其他的功能比如能自动生成帮助文档等。4使用click模块click模块是一个Python第三方库用于编写命令行工具。click模块提供了易用、功能强大的API能够帮助我们轻松地编写出高质量的命令行工具。下面是一个使用click模块的例子。​​​​​​​import click click.command() click.option(-i, --input, typeclick.Path(existsTrue), helpinput file name) click.option(-o, --output, typeclick.Path(), helpoutput file name) def main(input, output): click.echo(finput file: {input}) click.echo(foutput file: {output}) if __name__ __main__: main()上面的代码使用click模块获取命令行参数并打印出了获取到的参数。示例输出如下​​​​​​​$ python example.py -i input.txt -o output.txt input file: input.txt output file: output.txt在上述输出中程序正确解析了-i和-o参数并分别对应了input和output变量。click模块的API非常简洁明了能够帮助我们轻松地编写出高质量的命令行工具。以上四种方式都可以使用Python命令行参数化使用可以根据自己的需求选择适合自己的方式。