Python自学教程第二课:命令行参数

精华 发表在    Python教程部落 10-10 17:26:41

1 2532 0

Python提供了一个getopt模块,用于解析命令行选项和参数。

$ python test.py arg1 arg2 arg3

Python sys模块通过sys.argv提供对任何命令行参数的访问。主要有两个参数变量:

  • sys.argv是命令行参数的列表。
  • len(sys.argv)是命令行参数的数量。

这里sys.argv [0]是程序名称,即脚本的名称。比如在上面示例代码中,sys.argv [0]的值就是 test.py。

[示例]

看看以下脚本command_line_arguments.py的代码:


#!/usr/bin/python3import sysprint ('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])


当在参数列表中有一个无法识别的选项,或者当需要一个参数的选项不为任何参数时,会引发这个异常。异常的参数是一个字符串,指示错误的原因。 属性msg和opt给出错误消息和相关选项。

[示例]

假设想通过命令行传递两个文件名,也想给出一个选项用来显示脚本的用法。脚本的用法如下:


usage: file.py -i -o


#!/usr/bin/python3import sys, getoptdef 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 -o ')      sys.exit(2)   for opt, arg in opts:      if opt == '-h':         print ('usage: command_line_usage.py -i -o ')         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 -o

F:\worksp\python>python command_line_usage.py -i inputfile.txt -o GetoptError, usage: command_line_usage.py -i -o

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>




登录或注册后发布评论