python编写请求参数带文件_转载:如何编写一个带命令行参数的Python文件
看到別人執(zhí)行一個支持命令行參數(shù)的python文件,瞬間覺得高大上起來、牛逼起來,那么如何編寫一個帶命令行參數(shù)的python腳本呢?不用緊張,下面將簡單易懂地讓你學會如何讓自己的python腳本,支持命令行參數(shù)。
首先你要知道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程序使用命令行參數(shù),必不可少的模塊,就是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']
最后實戰(zhàn)一個例子吧!
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()
測試結(jié)果:
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
總結(jié)
以上是生活随笔為你收集整理的python编写请求参数带文件_转载:如何编写一个带命令行参数的Python文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梯度消失和梯度爆炸_知识干货-动手学深度
- 下一篇: python os.walk模块_Pyt