sys.argv變量是一個(gè)字符串的列表。特別地,sys.argv包含了命令行參數(shù) 的列表,即使用命令行傳遞給你的程序的參數(shù)。
這里,當(dāng)我們執(zhí)行python using_sys.py we are arguments的時(shí)候,我們使用python命令運(yùn)行using_sys.py模塊,后面跟著的內(nèi)容被作為參數(shù)傳遞給程序。Python為我們把它存儲(chǔ)在sys.argv變量中。記住,腳本的名稱總是sys.argv列表的第一個(gè)參數(shù)。所以,在這里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。注意,Python從0開始計(jì)數(shù),而非從1開始。
sys.argv[]是用來獲取命令行參數(shù)的,sys.argv[0]表示代碼本身文件路徑;比如在CMD命令行輸入 “python test.py -help”,那么sys.argv[0]就代表“test.py”。
sys.startswith() 是用來判斷一個(gè)對(duì)象是以什么開頭的,比如在python命令行輸入“'abc'.startswith('ab')”就會(huì)返回True
以下實(shí)例參考:
代碼如下:
#!/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
新聞熱點(diǎn)
疑難解答
圖片精選