首页 > 编程 > Python > 正文

python采用getopt解析命令行输入参数实例

2020-02-23 05:54:12
字体:
来源:转载
供稿:网友

本文实例讲述了python采用getopt解析命令行输入参数的方法,分享给大家供大家参考。

具体实例代码如下:

import getopt import sys  config = {   "input":"",   "output":".",    }  #getopt三个选项,第一个一般为sys.argv[1:],第二个参数为短参数,如果参数后面必须跟值,须加:,第三个参数为长参数 #是一个列表, opts, args = getopt.getopt(sys.argv[1:], 'hi:o:d',     [     'input=',      'output=',      'help'     ]    )  #参数的解析过程,长参数为--,短参数为- for option, value in opts:   if option in ["-h","--help"]:     print """     usage:%s --input=[value] --output=[value]     usage:%s -input value -o value     """   elif option in ['--input', '-i']:     config["input"] = value   elif option in ['--output', '-o']:     config["output"] = value   elif option == "-d":     print "usage -d"  print config  

输入的参数:

--input=c:/temp/aa -o c:/temp/output -d

打印的结果:

usage -d{'input': 'c://temp//aa', 'output': 'c://temp//output'}

希望本文所述对大家的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表