getopt例子

简介:

(本例基于win7 + python3.4)

复制代码
import getopt, sys
'''
getopt 模块专门用来处理命令行参数

函数
getopt(args, shortopts, longopts = [])

参数
    args       一般是sys.argv[1:]
    shortopts  短格式 (-) 
    longopts   长格式(--) 

如:
options, args = getopt.getopt(sys.argv[1:], "hp:i:", ["help", "ip=", "port="])

参数分析:
sys.argv[1:]
    --- sys.argv[0]  第一个参数,是脚本文件名
    --- sys.argv[1:] 第二个及后面的参数,是脚本文件运行所需的参数

"hp:i:"
    短格式 (shortopts)
    --- h 后面没有冒号:表示后面不带参数
    --- p:和 i:后面有冒号表示后面需要参数

["help", "ip=", "port="]
    长格式 (longopts)
    --- help后面没有等号=,表示后面不带参数
    --- 其他两个有等号=,表示后面需要参数

options
    返回值
    --- 是个包含元祖的列表,每个元组是分析出来的格式信息,比如 [('-i','127.0.0.1'),('-p','80')] ;

args
    返回值
    ---是个列表,包含那些没有'-'或'--'的参数,比如:['hello','world','you']

注意:定义命令行参数时,要先定义带'-'选项的参数,再定义没有'-'的参数


使用示例:
 $ python test.py -i 127.0.0.1 -p 80 hello world you

 $ python test.py --ip=127.0.0.1 --port=80 hello world you
'''
def usage():
    print('Usage:')
    print('     -h --help')
    print('     -i --ip')
    print('     -p --port')
    print('Example:')
    print('     $ python test.py -i 127.0.0.1 -p 80 hello world')
    print('     $ python test.py --ip=127.0.0.1 --port=80 hello world')

try:
    options, args = getopt.getopt(sys.argv[1:], "hp:i:", ["help", "ip=", "port="])
except getopt.GetoptError as err:
    print('Error:')
    print('    ', str(err))
    usage()
    sys.exit(2)

for opt, value in options:
    if opt in ("-h", "--help"):
        usage()
    elif opt in ("-i", "--ip"):
        print('ip:', value)
    elif opt in ("-p", "--port"):
        print('port:', value)

for value in args:
    print(value)
复制代码

 

【运行效果图】

本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/4349257.html ,如需转载请自行联系原作者
相关文章
|
8月前
|
容器
常用库函数的用法——memset() / swap() / reverse() / unique()函数的用法
常用库函数的用法——memset() / swap() / reverse() / unique()函数的用法
53 0
|
8月前
|
编译器 C语言 C++
define与const关键字的多种用法
define与const关键字的多种用法
89 0
while(~scanf(“%d“,&a)&&~a)用法
while(~scanf(“%d“,&a)&&~a)用法
135 0
|
Linux 程序员 编译器
【C语言】Sleep()函数----详解
【C语言】Sleep()函数----详解
674 0
|
存储 C语言
【C语言】 --- getopt()函数的使用简析
【C语言】 --- getopt()函数的使用简析
174 0
|
C语言
C语言 --- sprintf用法
C语言 --- sprintf用法
120 0
|
安全 编译器 数据库
C语言学习——sprintf函数详细解释及其用法
C语言学习——sprintf函数详细解释及其用法
782 0
|
C语言 机器学习/深度学习