Python sys.argv用法執行個體

來源:互聯網
上載者:User
sys.argv變數是一個字串的列表。特別地,sys.argv包含了命令列參數 的列表,即使用命令列傳遞給你的程式的參數。

這裡,當我們執行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開始。

sys.argv[]是用來擷取命令列參數的,sys.argv[0]表示代碼本身檔案路徑;比如在CMD命令列輸入 “python test.py -help”,那麼sys.argv[0]就代表“test.py”。

sys.startswith() 是用來判斷一個對象是以什麼開頭的,比如在python命令列輸入“'abc'.startswith('ab')”就會返回True
以下執行個體參考:
複製代碼 代碼如下:


#!/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
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.