如何編寫一個帶命令行參數的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( argsoptions[,  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 <inputfile> -o <outputfile>"
            print "or sysargv.py --infile <inputfile> --outfile <outputfile>"

        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 <inputfile> -o <outputfile>
or sysargv.py --infile <inputfile> --outfile <outputfile>
inputfile: None
outputfile: None
False

C:\Python27>python sysargv.py -h
sysargv.py -i <inputfile> -o <outputfile>
or sysargv.py --infile <inputfile> --outfile <outputfile>
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
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM