编写带命令行参数的 Python 程序

我们在安装一些 Python 程序的时候经常会输入这样的命令行语句 python setup.py install,从这条语句中我们可以看到 setup.py 是一个 Python 程序,但是其中的 install 又是什么呢?其实它就是这个 Python 程序的命令行参数。在这篇文章中我会和大家探讨 Python 程序中命令行参数的工作机制和如何去编写一个带命令行参数的 Python 程序。

Python 是如何识别出命令行参数的

sys 模块

在 Python 中,sys 模块是一个非常常用且十分重要的模块,通过模块中的 sys.argv 就可以访问到所有的命令行参数,它的返回值是包含所有命令行参数的列表(list),下面我们通过程序来说明它的用法:


import sys

print 'Number of arguments:', len(sys.argv)

print 'They are:', str(sys.argv)

运行以及结果:

python ./test_argv.py arg0 arg1 arg2
Number of arguments: 4
They are: ['./test_argv.py', 'arg0', 'arg1', 'arg2']

我们看到通过 sys.argv 我们可以获得运行 Python 程序中所有的命令行参数。

getopt 模块

谈到 Python 的命令行参数,有一个模块是不得不提的,那就是 getopt,我们先来看一下这个函数:

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

我们先来看一下里面参数的含义:

  • args: 表示的是要被处理的命令行参数列表(通常是通过上述的 sys.argv 获得的结果)

  • options: 它表示的是命令行参数中的选项,通常是一个字母,就像我们在 Linux 中对于某个命令不熟悉时所使用的帮助选项-h一样。如果说该选项需要一个参数的话,需要在该字母后边加上一个冒号:,表示该选项需要一个参数(如果这句不明白可以看下边的示例程序)

  • long_options: 它是一个可选的参数,表示的是选项的长格式,上边的options是短格式,长格式的选项的参数格式示例为--input=input.txt,具体如何使用,详见下边的示例程序。

编写一个带命令行的 Python 程序

了解了 sys 模块和 getopt 模块,我们就可以来自己编写一个带有命令行的程序并且在该程序中,我们还使用了 getopt.GetoptError 来进行异常处理。代码如下:

# -*- coding:utf-8 -*- 

import sys, getopt

def main(argv):
    inputfile = ""
    outputfile = ""

    try:
        # 这里的 h 就表示该选项无参数,i:表示 i 选项后需要有参数
        opts, args = getopt.getopt(argv, "hi:o:",["infile=", "outfile="])
    except getopt.GetoptError:
        print 'Error: test_arg.py -i <inputfile> -o <outputfile>'
        print '   or: test_arg.py --infile=<inputfile> --outfile=<outputfile>'
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print 'test_arg.py -i <inputfile> -o <outputfile>'
            print 'or: test_arg.py --infile=<inputfile> --outfile=<outputfile>'

            sys.exit()
        elif opt in ("-i", "--infile"):
            inputfile = arg
        elif opt in ("-o", "--outfile"):
            outputfile = arg

    print 'Input file : ', inputfile
    print 'Output file: ', outputfile

if __name__ == "__main__":
    main(sys.argv[1:])

运行结果:

./test_arg.py
Input file :
Output file:
python ./test_arg.py -h
test_arg.py -i <inputfile> -o <outputfile>
or: test_arg.py --infile=<inputfile> --outfile=<outputfile>
python ./test_arg.py -a
Error: test_arg.py -i <inputfile> -o <outputfile>
   or: test_arg.py --infile=<inputfile> --outfile=<outputfile>
python ./test_arg.py -i in.txt -o out.txt
Input file :  in.txt
Output file:  out.txt
Cookies  python ./test_arg.py --infile=in.txt
Input file :  in.txt
Output file:

本文的版权归作者 罗远航 所有,采用 Attribution-NonCommercial 3.0 License。任何人可以进行转载、分享,但不可在未经允许的情况下用于商业用途;转载请注明出处。感谢配合!

发布了105 篇原创文章 · 获赞 237 · 访问量 28万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章