看到别人执行一个支持命令行参数的 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)
- #上述程序的文件名sysargv.py
- python sysargv.py argv1 argv2 argv3 argv4
- the number of python program's argument: 5the value of every argumentis['sysargv.py','argv1','argv2','argv3','argv4']
其次,python 程序使用命令行参数,必不可少的模块,就是 getopt 模块, 先看看一段代码
- getopt.
(args,options[,long_options])
- 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
- forkey,valuein opts:
- ifkey=="-v":
- verbose=True
- elifkeyin("-h","--help"):
- print "sysargv.py -i <inputfile> -o <outputfile>"
- print "or sysargv.py --infile <inputfile> --outfile <outputfile>"
- elifkeyin("-i","--infile"):
- infile = value
- elifkeyin("-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
- orsysargv.py --infile --outfile
- inputfile: None
- outputfile: None
- False
- C:\Python27>python sysargv.py -h
- sysargv.py -i -o
- orsysargv.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
来源: http://www.cnblogs.com/wc554303896/p/7078392.html