pythongetopt模块是什么

python中getopt模块是什么

1、Getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数。命令行选项使程序参数更加灵活,支持短选项模式(-)和长选项模式(-)。

2、该模块提供了两种方法和一种异常处理来分析命令行参数。

实例

importsys

importgetopt

defmain(argv):

input_file=""

output_file=""

#"hi:o:":短格式分析串,h后面没有冒号,表示后面不带参数;i和o后面带有冒号,表示后面带参数

#["help","input_file=","output_file="]:长格式分析串列表,help后面没有等号,表示后面不带参数;input_file和output_file后面带冒号,表示后面带参数

#返回值包括optsargs,opts是以元组为元素的列表,每个元组的形式为:(选项,附加参数),如:('-i','test.webp');

#args是个列表,其中的元素是那些不含'-'或'--'的参数

opts,args=getopt.getopt(argv[1:],"hi:o:",["help","input_file=","output_file="])

foropt,arginopts:

ifoptin("-h","--help"):

print('script_2.py-i-o')

print('or:test_arg.py--input_file=--output_file=')

sys.exit()

elifoptin("-i","--input_file"):

input_file=arg

elifoptin("-o","--output_file"):

output_file=arg

print('输入文件为:',input_file)

print('输出文件为:',output_file)

#打印不含'-'或'--'的参数

foriinrange(0,len(args)):

print('不含'-'或'--'的参数%s为:%s'%(i+1,args[i]))

if__name__=="__main__":

main(sys.argv)

以上内容为大家介绍了python培训之getopt模块是什么,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注我们

推荐阅读