今天又好好學(xué)習(xí)了一把,總算是大徹大悟了。
Sys.argv[]是用來獲取命令行參數(shù)的,sys.argv[0]表示代碼本身文件路徑,所以參數(shù)從1開始,以下兩個例子說明:
1、使用sys.argv[]的一簡單實例,
1 import sys,os
2 os.system(sys.argv[1])
這個例子os.system接收命令行參數(shù),運行參數(shù)指令,保存為sample1.py,命令行帶參數(shù)運行sample1.py
notepad,將打開記事本程序。
2、這個例子是簡明python教程上的,明白它之后你就明白sys.argv[]了。
1 import sys
2 def readfile(filename): #從文件中讀出文件內(nèi)容
3 '''''Print a file to the standard output.'''
4 f = file(filename)
5 while True:
6 line = f.readline()
7 if len(line) == 0:
8 break
9 print line, # notice comma 分別輸出每行內(nèi)容
10 f.close()
11 # Script starts from here
12 if len(sys.argv) < 2:
13 print 'No action specified.'
14 sys.exit()
15 if sys.argv[1].startswith('--'):
16 option = sys.argv[1][2:]
17 # fetch sys.argv[1] but without the first two characters
18 if option == 'version': #當(dāng)命令行參數(shù)為-- version,顯示版本號
19 print 'Version 1.2'
20 elif option == 'help': #當(dāng)命令行參數(shù)為--help時,顯示相關(guān)幫助內(nèi)容
21 print '''''\
22 This program prints files to the standard output.
23 Any number of files can be specified.
24 Options include:
25 --version : Prints the version number
26 --help : Display this help'''
27 else:
28 print 'Unknown option.'
29 sys.exit()
30 else:
31 for filename in sys.argv[1:]: #當(dāng)參數(shù)為文件名時,傳入readfile,讀出其內(nèi)容
32 readfile(filename)
33
保存程序為sample.py.我們驗證一下:
<!--[if !supportLists]-->1)
<!--[endif]-->命令行帶參數(shù)運行:sample.py
–version 輸出結(jié)果為:version
1.2
<!--[if !supportLists]-->2)
<!--[endif]-->命令行帶參數(shù)運行:sample.py
–help 輸出結(jié)果為:This program prints
files……
<!--[if !supportLists]-->3)
<!--[endif]-->在與sample.py同一目錄下,新建a.txt的記事本文件,內(nèi)容為:test argv;命令行帶參數(shù)運行:sample.py
a.txt,輸出結(jié)果為a.txt文件內(nèi)容:test
argv,這里也可以多帶幾個參數(shù),程序會先后輸出參數(shù)文件內(nèi)容。
posted on 2009-08-01 10:43
老馬驛站 閱讀(11761)
評論(0) 編輯 收藏 引用 所屬分類:
python