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

yipeiwu_com5年前Python基础

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

相关文章

详解Python中find()方法的使用

 find()方法判断字符串str,如果起始索引beg和结束end索引能找到在字符串或字符串的一个子串中。 语法 以下是find()方法的语法: str.find(str,...

实现Python与STM32通信方式

实现Python与STM32通信方式

断断续续学了几周Stm32后,突然想实现上位机和下位机的通信,恰好自己学过一点python,便想通过python实现通信. 在网上看见python库pyserial可以实现此功能,便去官...

nohup后台启动Python脚本,log不刷新的解决方法

问题: =》nohup python3 xxxx.py &后台启动脚本 tail -100f nohup.out    -------->  &nbs...

Python设计模式中单例模式的实现及在Tornado中的应用

Python设计模式中单例模式的实现及在Tornado中的应用

单例模式的实现方式 将类实例绑定到类变量上 class Singleton(object): _instance = None def __new__(cls, *args...

Windows和Linux下Python输出彩色文字的方法教程

Windows和Linux下Python输出彩色文字的方法教程

前言 最近在项目中需要输出彩色的文字来提醒用户,以前写过,但是只能在win上面运行。 今天搜了下看有没有在win和Linux上通用的输出彩色文字的模块,结果发现没有,,于是就自己弄了一个...