編寫帶命令行參數的 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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章