sys.argv[]用法

Sys.argv[]是用來獲取命令行參數的,sys.argv[0]表示代碼自己文件路徑,因此參數從1開始,如下兩個例子說明:

import sys
def readfile(filename):  #從文件中讀出文件內容
    '''Print a file to the standard output.'''
    f = file(filename)
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print line, # notice comma  分別輸出每行內容
    f.close()
# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()
if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':  #當命令行參數爲-- version,顯示版本號
        print 'Version 1.2'
    elif option == 'help':  #當命令行參數爲--help時,顯示相關幫助內容
        print '''/
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help'''
    else:
        print 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1:]: #當參數爲文件名時,傳入readfile,讀出其內容
        readfile(filename)
保存程序爲sample.py.咱們驗證一下: 1) 命令行帶參數運行:sample.py –version 輸出結果爲:version 1.2 2) 命令行帶參數運行:sample.py –help 輸出結果爲:This program prints files…… 3) 在與sample.py同一目錄下,新建a.txt的記事本文件,內容爲:test argv;命令行帶參數運行:sample.py a.txt,輸出結果爲a.txt文件內容:test argv,這裏也能夠多帶幾個參數,程序會前後輸出參數文件內容。
相關文章
相關標籤/搜索