sys.argv變量是一個字符串的列表。特別地,sys.argv包含了命令行參數 的列表,即便用命令行傳遞給你的程序的參數。python
這裏,當咱們執行python using_sys.py we are arguments的時候,咱們使用python命令運行using_sys.py模塊,後面跟着的內容被做爲參數傳遞給程序。Python爲咱們把它存儲在sys.argv變量中。記住,腳本的名稱老是sys.argv列表的第一個參數。因此,在這裏,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。注意,Python從0開始計數,而非從1開始。ide
sys.argv[]是用來獲取命令行參數的,sys.argv[0]表示代碼自己文件路徑;好比在CMD命令行輸入 「python test.py -help」,那麼sys.argv[0]就表明「test.py」。sys.startswith() 是用來判斷一個對象是以什麼開頭的,好比在python命令行輸入「'abc'.startswith('ab')」就會返回Truefetch
如下實例參考:this
#!/usr/local/bin/env python 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, f.close() print "sys.argv[0]---------",sys.argv[0] print "sys.argv[1]---------",sys.argv[1] print "sys.argv[2]---------",sys.argv[2] # 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': print 'Version 1.2' elif option == '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(filename) 執行結果:# python test.py --version help sys.argv[0]--------- test.py sys.argv[1]--------- --version sys.argv[2]--------- help Version 1.2注意:sys.argv[1][2:]表示從第二個參數,從第三個字符開始截取到最後結尾,本例結果爲:version