python命令行参数和批文件_如何编写一个带命令行参数的Python文件

看到别人执行一个支持命令行参数的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: 5

the value of every argument is ['sysargv.py', 'argv1', 'argv2', 'argv3', 'argv4']

其次,python程序使用命令行参数,必不可少的模块,就是getopt 模块,先看看一段代码

getopt.getopt(args, options[, long_options])

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值