课程表

Python 基础教程

Python 高级教程

工具箱
速查手册

Python 命令行参数

当前位置:免费教程 » 程序设计 » Python

Python 提供了 getopt 模块来获取命令行参数。

  1. $ python test.py arg1 arg2 arg3

Python 中也可以所用 syssys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 是命令行参数个数。

注:sys.argv[0] 表示脚本名。

实例

test.py 文件代码如下:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import sys
  5.  
  6. print '参数个数为:', len(sys.argv), '个参数。'
  7. print '参数列表:', str(sys.argv)

执行以上代码,输出类似如下的结果:

  1. $ python test.py arg1 arg2 arg3
  2. 参数个数为: 4 个参数。
  3. 参数列表: ['test.py', 'arg1', 'arg2', 'arg3']

getopt模块

getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式(-)和长选项模式(--)。

该模块提供了两个方法及一个异常处理来解析命令行参数。

getopt.getopt 方法

getopt.getopt 方法用于解析命令行参数列表,语法格式如下:

  1. getopt.getopt(args, options[, long_options])

方法参数说明:

  • args: 要解析的命令行参数列表。

  • options: 以字符串的格式定义,options后的冒号(:)表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。

  • long_options: 以列表的格式定义,long_options 后的等号(=)表示如果设置该选项,必须有附加的参数,否则就不附加参数。

  • 该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有'-'或'--'的参数。

另外一个方法是 getopt.gnu_getopt,这里不多做介绍。


Exception getopt.GetoptError

在没有找到参数列表,或选项的需要的参数为空时会触发该异常。

异常的参数是一个字符串,表示错误的原因。属性 msgopt 为相关选项的错误信息。

实例

假定我们创建这样一个脚本,可以通过命令行向脚本文件传递两个文件名,同时我们通过另外一个选项查看脚本的使用。脚本使用方法如下:

  1. usage: test.py -i <inputfile> -o <outputfile>

test.py 文件代码如下所示:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import sys, getopt
  5.  
  6. def main(argv):
  7. inputfile = ''
  8. outputfile = ''
  9. try:
  10. opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
  11. except getopt.GetoptError:
  12. print 'test.py -i <inputfile> -o <outputfile>'
  13. sys.exit(2)
  14. for opt, arg in opts:
  15. if opt == '-h':
  16. print 'test.py -i <inputfile> -o <outputfile>'
  17. sys.exit()
  18. elif opt in ("-i", "--ifile"):
  19. inputfile = arg
  20. elif opt in ("-o", "--ofile"):
  21. outputfile = arg
  22. print '输入的文件为:', inputfile
  23. print '输出的文件为:', outputfile
  24.  
  25. if __name__ == "__main__":
  26. main(sys.argv[1:])

执行以上代码,输出结果为:

  1. $ python test.py -h
  2. usage: test.py -i <inputfile> -o <outputfile>
  3.  
  4. $ python test.py -i inputfile -o outputfile
  5. 输入的文件为: inputfile
  6. 输出的文件为: outputfile
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号