python 命令行参数分析
以下是代码——————————————————————
import sys
import getopt
def main(argv):
input_file = ""
output_file = ""
# "hi:o:": 短格式分析串, h 后面没有冒号, 表示后面不带参数; i 和 o 后面带有冒号, 表示后面带参数
# ["help", "input_file=", "output_file="]: 长格式分析串列表, help后面没有等号, 表示后面不带参数; input_file和output_file后面带冒号, 表示后面带参数
# 返回值包括 `opts` 和 `args`, opts 是以元组为元素的列表, 每个元组的形式为: (选项, 附加参数),如: ('-i', 'test.png');
# args是个列表,其中的元素是那些不含'-'或'--'的参数
opts, args = getopt.getopt(argv, "hi:o:", ["help", "input_file=", "output_file="])
for opt, arg in opts:
if opt in ("-h", "--help"):
print('script_2.py -i <input_file> -o <output_file>')
print('or: test_arg.py --input_file=<input_file> --output_file=<output_file>')
sys.exit()
elif opt in ("-i", "--input_file"):
input_file = arg
elif opt in ("-o", "--output_file"):
output_file = arg
print('输入文件为:', input_file)
print('输出文件为:', output_file)
# 打印不含'-'或'--'的参数
for i in range(0, len(args)):
print('不含'-'或'--'的参数 %s 为:%s' % (i + 1, args))
if __name__ == "__main__":
main(sys.argv)
——————————————————————————————
1.不太理解为什么加红文字opts是元素为元组的列表。
2.还有在命令行输入时,为什么不含'-'或'--'会存到args里面,是哪一行代码实现了这个功能? 两个问题:
1.为什么是元组?
getopt的func的源代码为,设定就是这样的:
def getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list.args is the
argument list to be parsed, without the leading reference to the
running program.Typically, this means "sys.argv".shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses).If
specified, longopts is a list of strings with the names of the
long options which should be supported.The leading '--'
characters should not be included in the option name.Options
which require an argument should be followed by an equal sign
('=').
The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument).Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument.The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences.Long and short options may be mixed.
"""
opts = []
if type(longopts) == type(""):
longopts =
else:
longopts = list(longopts)
while args and args.startswith('-') and args != '-':
if args == '--':
args = args
break
if args.startswith('--'):
opts, args = do_longs(opts, args, longopts, args)
else:
opts, args = do_shorts(opts, args, shortopts, args)
return opts, args
2.为什么会自动处理-和--?
可以参考源码进行解读,源码路径如下(python路径请替换为自己的安装路径)
C:\python\Lib\getopt.py
如果实在找不到,可以下载一个everything去找getopt.py,一共不到两百行,相信你很快就能看明白。
页:
[1]