• 如何编写一个带命令行参数的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 <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
  • 相关阅读:
    java处理图片--图片的缩放,旋转和马赛克化
    Node.JS + MongoDB技术浅谈
    nodejs版本更新问题:express不是内部或外部命令
    解决mongodb的安装mongod命令不是内部或外部命令
    MongoDB Windows环境安装及配置
    WebStorm主题设置
    分页插件PageHelper
    Dubbo入门
    JVM组成
    java 多线程例子
  • 原文地址:https://www.cnblogs.com/wc554303896/p/7078392.html
Copyright © 2020-2023  润新知