目录
getopt函数简介
运行程序时,根据不同的条件,输入不同的命令行选项实现不同的功能。getopt函数支持短选项和长选项两种格式。短选项的格式为"-"加上一个字母;长选项为"--"加上一个单词。
getopt模块有两个函数
- getopt.getopt
- getoptgnu_getopt
其中最常用的是getopt.getopt函数:
getopt.getopt(args,shortopts,longopts=[])
- args指的是当前脚本接受的参数,是一个列表,通过sys.argv获得
- shortopts 短参数 例如 -h
- longopts 长参数. 例如 --help
实例演示
入门级
import getopt
import sys
opt = getopt.getopt(sys.argv[1:],'-h',['help'])
print(opt)
#输出结果
python 1.py -h
([('-h', '')], [])
python 1.py -help
([('--help', '')], [])
小型脚本-读取文件
#导入需要的模块
import getopt
import sys
#定义读取文件的函数
def readfiles(txt):
with open(txt,"r") as f:
print(f.read())
#'-v -h -r:'为短参数,如果参数后面需要带值,则必须在参数后面加上":"
#['version','help','readfile=']为长参数,如果参数后面需要带值,则必须在参数后面加上"="
#opts是一个两元组的列表,每个元素为(选项,附加参数)如果没有附加参数则为空
opts,args =getopt.getopt(sys.argv[1:],'-v -h -r:',['version','help','readfile='])
for opt_name,opt_value in opts:
if opt_name in ('-h','--help'):
print ('''
Option include:
--version : prints the version information
--readfile : read files
--help : Display this help
''')
elif opt_name in ('-v','--version'):
print("version 1.2")
elif opt_name in ('-r','--readfile'):
readfiles(opt_value)
else:
print("Error Option")
#输出结果
python 1.py -v
version 1.2
python 1.py -h
Option include:
--version : prints the version information
--readfile : read files
--help : Display this help
python 1.pt -r 1.txt
i love you