Python getopt模块处理命令行选项实例

yipeiwu_com6年前Python基础

getopt模块用于抽出命令行选项和参数,也就是sys.argv
命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式
例如  python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'

复制代码 代码如下:

import getopt, sys
shortargs = 'f:t'
longargs = ['directory-prefix=', 'format']
opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

getopt.getopt ( [命令行参数列表], '短选项', [长选项列表] )

短选项名后的冒号 : 表示该选项必须有附加的参数
长选项名后的等号 = 表示该选项必须有附加的参数

返回 opts 和 args
opts 是一个参数选项及其value的元组 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )  

复制代码 代码如下:
# 然后遍历 opts 便可以获取所有的命令行选项及其对应参数了
for opt, val in opts:
    if opt in ( '-f', '--format' ):
        pass
    if ....

使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮

# 两个来自 python2.5 Documentation 的例子

复制代码 代码如下:

>>> import getopt, sys
>>> arg = '-a -b -c foo -d bar a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' )
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

>>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] )
>>> optlist
[ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ]
>>> args
['a1', 'a2']

相关文章

python使用win32com在百度空间插入html元素示例

复制代码 代码如下:from win32com.client import DispatchEximport timeie=DispatchEx("InternetExplorer.Ap...

详解Python3 基本数据类型

详解Python3 基本数据类型

Python3 基本数据类型 Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。 在 Python 中,变量就是变量,它没有类型,我们所说的"类...

Python实现判断一个字符串是否包含子串的方法总结

本文实例总结了Python实现判断一个字符串是否包含子串的方法。分享给大家供大家参考,具体如下: 1.使用成员操作符 in >>> s='nihao,shijie'...

通过实例浅析Python对比C语言的编程思想差异

通过实例浅析Python对比C语言的编程思想差异

我一直使用 Python,用它处理各种数据科学项目。 Python 以易用闻名。有编码经验者学习数天就能上手(或有效使用它)。 听起来很不错,不过,如果你既用 Python,同时也是用其...

Python中查看文件名和文件路径

查看文件名和文件路径 >>> import os >>> url = 'http://images.cnitblog.com/i/311516/2...