简书链接:批处理编写进阶解读
文章字数:152,阅读全文大约需要1分钟

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/python3

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"h:i:o:",["infile=","outfile="])
except getopt.GetoptError:
print ('GetoptError, usage: command_line_usage.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
print("opt:"+opt+",arg:"+arg)
if opt == '-h':
print ('usage: command_line_usage.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--infile"):
inputfile = arg
elif opt in ("-o", "--outfile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)

if __name__ == "__main__":
main(sys.argv[1:])

这是典型的命令行传递参数,
支持传递的语法
python xxx.py -i 输入 -o 输出
python xxx.py --infile 输入 -outfile 输出
另外
python xxx.py -h
获取帮助信息

那么输入python xxx.py xxxx如何得到信息呢?我上面对h进行勒修改改成勒h:如果去掉冒号,是无法取到值.但是必须传递值,否则就会走异常代码块勒