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

WBOY
Release: 2016-06-16 08:41:30
Original
1014 people have browsed it

本文实例讲述了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  
Copy after login

输入的参数:

--input=c:\temp\aa -o c:\temp\output -d
Copy after login

打印的结果:

usage -d
{'input': 'c:\\temp\\aa', 'output': 'c:\\temp\\output'}
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!