使用命令行窗口执行某些py文件时,往往会传入一些参数,如:
python practise.py --help='this is my name' -v 20
上述这种使用命令行传参的执行方式,在很多场景中都会用到。通过getopt.getopt()
可以提取到这些参数。
函数的源代码如下:
def getopt(args, shortopts, longopts = []):
"""args和shortopts属于必传参数,longopts为非必传参数"""
opts = []
if type(longopts) == type(""):
longopts = [longopts]
else:
longopts = list(longopts)
while args and args[0].startswith('-') and args[0] != '-':
if args[0] == '--':
args = args[1:]
break
if args[0].startswith('--'): # 用来处理长参数
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
else: # 用来处理短参数
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
return opts, args
def getopt(args, shortopts, longopts = []):
"""
params:args是用来解析的命令行字符串,通常为sys.argv[1:]
params:shortopts是用来匹配命令行中的短参数,为字符串类型
parmas:longopts是用来匹配命令行中的长参数,为列表类型
return:opts为列表嵌套元组类型,用来存放解析好的参数和值
return:args为列表类型,用来存放不匹配的命令行参数
"""
...
return opts, args
对应命令行传参可分为以下七种情况:
此时getopt的shortopts应传入"v",即getopt.getopt(args, "v")
import sys
import getopt
if __name__ == "__main__":
opts, args = getopt.getopt(sys.argv[1:], "v")
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py -v
输出结果:
opts is [('-v', '')]
args is []
此时getopt的shortopts应传入"v:",即getopt.getopt(args, "v:")
import sys
import getopt
if __name__ == "__main__":
opts, args = getopt.getopt(sys.argv[1:], "v:")
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py -v 20
输出结果:
opts is [('-v', '20')]
args is []
此时getopt的shortopts应传入"f:v:"
,即getopt.getopt(args, "f:v:")
import sys
import getopt
if __name__ == "__main__":
opts, args = getopt.getopt(sys.argv[1:], "f:v:")
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py -v 20 -f demo
输出结果:
opts is [('-v', '20'), ('-f', 'demo')]
args is []
此时getopt的longopts应传入[“filename=”],即getopt.getopt(args, "", ["filename="])
import sys
import getopt
if __name__ == "__main__":
# shortopts是必传参数,不可省略,传入''也行
opts, args = getopt.getopt(sys.argv[1:], "", longopts=["filename="])
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py --filename=
输出结果:
opts is [('--filename', '')]
args is []
此时getopt的longopts应传入[“filename=”],即getopt.getopt(args, "f:", ["filename="])
import sys
import getopt
if __name__ == "__main__":
# shortopts是必传参数,不可省略,传入''也行
opts, args = getopt.getopt(sys.argv[1:], "", longopts=["filename="])
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py --filename=demo
输出结果:
opts is [('--filename', 'demo')]
args is []
此时getopt的longopts应传入[“filename=”, “version=”],即getopt.getopt(args, "f:", ["filename=", "version="])
import sys
import getopt
if __name__ == "__main__":
# shortopts是必传参数,不可省略,传入''也行
opts, args = getopt.getopt(sys.argv[1:], "", longopts=["filename=", "version="])
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py --filename=demo --version=20
输出结果:
opts is [('--filename', 'demo'), ('--version', '20')]
args is []
import sys
import getopt
if __name__ == "__main__":
# shortopts是必传参数,不可省略,传入''也行
opts, args = getopt.getopt(sys.argv[1:], "f:v:", longopts=["filename=", "version="])
print("opts is ", opts)
print("args is ", args)
调用方式:
python practise.py --filename=demo -v 20
输出结果:
opts is [('--filename', 'demo'), ('-v', '20')]
args is []
python practise.py -s this is my name
这种情况,最终获得的结果为opts is [('-h', 'this')]
args is ['is', 'my', 'name']
# 由此示例可知,args是用来存用不匹配的命令行输入参数
解决方案:# 使用如下命令
python practise.py -h 'this is my name'
# 最终结果为:
opts is [('-h', 'this is my name')]
args is []
-参数名(空格)值
--参数名=值
this is my name
中间有空格的字符串,则需要使用’'将其括起# 导包
import argparse
def parse_args():
# 创建参数解析器
parser = argparse.ArgumentParser(description="this is a demo")
help = "this is an integer"
# 添加参数
parser.add_argument("integer", nargs="+", type=int, required=True, help=help)
# 调用parse_args解析命令行参数
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
# 通过args.参数名即可获取参数值
print(args.integer)
# 1. getopt.getopt
opts, args =getopt.getopt(sys.argv[1:], "hf:v:", ["help", "filename=", "version"])
# opts中存放的是匹配的参数和对应的值
# 2. argparse
parser = argparse.ArgumentParser()
parser.add_argument(...) # 用来指定参数(位置参数和可选参数)
args = parser.parse_args()
# 通过args.参数名获取值
1. getopt不能预设值,即没有默认值,全依赖命令行的输入;argparse可以设置默认值,更加灵活
2. 应用场景不同,getopt更多应用于命令行输入参数值,开启某些功能,argparse则是摆脱IDEA的限制,很灵活的配置命令行参数(再议)
argparse模块的学习
getopt模块的学习