Python 提供了一个 getopt 模块, 用于解析命令行选项和参数.
- $ python test.py arg1 arg2 arg3
- Shell
Python sys 模块通过 sys.argv 提供对任何命令行参数的访问. 主要有两个参数变量 -
sys.argv 是命令行参数的列表.
len(sys.argv) 是命令行参数的数量.
这里 sys.argv [0] 是程序名称, 即脚本的名称. 比如在上面示例代码中, sys.argv [0] 的值就是 test.py.
示例
看看以下脚本 command_line_arguments.py 的代码 -
- #!/usr/bin/python3
- import sys
- print ('Number of arguments:', len(sys.argv), 'arguments.')
- print ('Argument List:', str(sys.argv))
现在运行上面的脚本, 这将产生以下结果 -
F:\>python F:\worksp\python\command_line_arguments.py
- Number of arguments: 1 arguments.
- Argument List: ['F:\\worksp\\python\\command_line_arguments.py']
- F:\>python F:\worksp\python\command_line_arguments.py arg1 arg2 arg3 arg4
- Number of arguments: 5 arguments.
- Argument List: ['F:\\worksp\\python\\command_line_arguments.py', 'arg1', 'arg2', 'arg3', 'arg4']
- F:\>
注意 - 如上所述, 第一个参数始终是脚本名称, 它也被计入参数的数量.
解析命令行参数
Python 提供了一个 getopt 模块, 可用于解析命令行选项和参数. 该模块提供了两个功能和异常, 以启用命令行参数解析.
getopt.getopt 方法
此方法解析命令行选项和参数列表. 以下是此方法的简单语法 -
getopt.getopt(args, options, [long_options])
getopt.GetoptError 异常
当在参数列表中有一个无法识别的选项, 或者当需要一个参数的选项不为任何参数时, 会引发这个异常.
异常的参数是一个字符串, 指示错误的原因. 属性 msg 和 opt 给出错误消息和相关选项.
示例
假设想通过命令行传递两个文件名, 也想给出一个选项用来显示脚本的用法. 脚本的用法如下 -
usage: file.py -i <inputfile> -o <outputfile>
以下是 command_line_usage.py 的以下脚本 -
- #!/usr/bin/python3
- import sys, getopt
- def main(argv):
- inputfile = '' outputfile =''
- try:
- opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
- except getopt.GetoptError:
- print ('GetoptError, usage: command_line_usage.py -i <inputfile> -o <outputfile>')
- sys.exit(2)
- for opt, arg in opts:
- if opt == '-h':
- print ('usage: command_line_usage.py -i <inputfile> -o <outputfile>')
- sys.exit()
- elif opt in ("-i", "--ifile"):
- inputfile = arg
- elif opt in ("-o", "--ofile"):
- outputfile = arg
- print ('Input file is"', inputfile)
- print ('Output file is"', outputfile)
- if __name__ == "__main__":
- main(sys.argv[1:])
现在, 使用以下几种方式运行来脚本, 输出如下所示:
- F:\worksp\python>python command_line_usage.py -h
- usage: command_line_usage.py -i <inputfile> -o <outputfile>
- F:\worksp\python>python command_line_usage.py -i inputfile.txt -o
- GetoptError, usage: command_line_usage.py -i <inputfile> -o <outputfile>
- F:\worksp\python>python command_line_usage.py -i inputfile.txt -o outputfile.txt
- Input file is " inputfile.txt
- Output file is " outputfile.txt
- F:\worksp\python>
来源: http://www.bubuko.com/infodetail-2972652.html