看到别人执行一个支持命令行参数的python文件,瞬间觉得高大上起来、牛逼起来,那么如何编写一个带命令行参数的python脚本呢?不用紧张,下面将简单易懂地让你学会如何让自己的python脚本,支持命令行参数。
首先你要知道python中的sys模块的一些功能:
import sys
print "the number of python program's argument:",len(sys.argv)
print "the value of every argument is ",str(sys.argv)
python sysargv.py argv1 argv2 argv3 argv4
the number of python program's argument: 5
the value of every argument is ['sysargv.py', 'argv1', 'argv2', 'argv3', 'argv4']
其次,python程序使用命令行参数,必不可少的模块,就是getopt 模块,先看看一段代码
import getopt
args = '-a -b -cfoo -d bar a1 a2'.split()
args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
optlist, args = getopt.getopt(args, 'abc:d:')
optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
args
['a1', 'a2']
使用long_options
s = '--condition=foo --testing --output-file abc.def -x a1 a2'
args = s.split()
args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
optlist, args = getopt.getopt(args, 'x', ['condition=', 'output-file=', 'testing'])
optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
args
['a1', 'a2']
最后实战一个例子吧!
import getopt,sys
def main():
try:
opts,args=getopt.getopt(sys.argv[1:],"hi:o:v",["help","infile=","outfile="])
except getopt.GetoptError as error:
print str(error)
usage()
sys.exit(2)
infile=None
output=None
verbose=False
for key,value in opts:
if key=="-v":
verbose=True
elif key in ("-h","--help"):
print "sysargv.py -i -o "
print "or sysargv.py --infile --outfile "
elif key in ("-i","--infile"):
infile = value
elif key in ("-o","--outfile"):
output= value
print "inputfile:", infile
print "outputfile:", output
print verbose
if __name__=="__main__":
main()
测试结果:
C:\Python27>python sysargv.py --help
sysargv.py -i -o
or sysargv.py --infile --outfile
inputfile: None
outputfile: None
False
C:\Python27>python sysargv.py -h
sysargv.py -i -o
or sysargv.py --infile --outfile
inputfile: None
outputfile: None
False
C:\Python27>python sysargv.py -i "inputfile1" -o "ouputfile2"
inputfile: inputfile1
outputfile: ouputfile2
False
C:\Python27>python sysargv.py -i "inputfile1"
inputfile: inputfile1
outputfile: None
False
C:\Python27>python sysargv.py -o "outputfile1"
inputfile: None
outputfile: outputfile1
False
C:\Python27>python sysargv.py -o "outputfile1" -v
inputfile: None
outputfile: outputfile1
True
C:\Python27>python sysargv.py --infile "inputfile" --outfile "outputfile1" -v
inputfile: inputfile
outputfile: outputfile1
True