Home  >  Article  >  Backend Development  >  python采用getopt解析命令行输入参数实例

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

WBOY
WBOYOriginal
2016-06-16 08:41:301130browse

本文实例讲述了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程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn