Python命令列參數sys.argv[]

來源:互聯網
上載者:User

標籤:nbsp   notepad   TE   play   copy   --help   n+1   下標   協助   

 

學習C語言的時候就沒弄明白命令列參數的用法,在學習Pyton 的時候又遇到了命令列參數,在這裡稍微學習了一下,稍微明白了一些在這裡做個記錄方便後面回顧複習。

Sys.argv[]是用來擷取命令列參數的,sys.argv[0]表示代碼檔案絕對路徑,所以所以其餘參數從1開始,以下兩個例子說明:

 

1、

import sys,os 
os.system(sys.argv[1])

這個例子os.system接收命令列參數,運行參數指令,儲存為sample1.py,命令列帶參數運行sample1.py notepad,將開啟記事本程式。

 

2、這個例子是簡明python教程上的,明白它之後你就明白sys.argv[]了。

1.    import sys  2.    def readfile(filename):  #從檔案中讀出檔案內容  ,這是被調函數但被傳參數為檔案名稱de時候調用該函數3.        ‘‘‘‘‘Print a file to the standard output.‘‘‘  4.        f = file(filename)  #開啟檔案,這裡和open效果一樣5.        while True:  6.            line = f.readline()  #讀取每行資訊7.            if len(line) == 0:  8.                break  9.            print line, # notice comma  分別輸出每行內容  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:]     #這是一個二維數組,把argv[1]這個參數的下標為[2]即第三個字元開始直到結束的字串
                        #複製給option 如果是--help,則這之後option為help17. # fetch sys.argv[1] but without the first two characters 18. if option == ‘version‘: #當命令列參數為-- version,顯示版本號碼 19. print ‘Version 1.2‘ 20. elif option == ‘help‘: #當命令列參數為--help時,顯示相關協助內容 及列印注釋的相關內容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:]: #當參數為檔案名稱時,傳入readfile,讀出其內容 32. 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,這裡也可以多帶幾個參數,程式會先後輸出參數檔案內容。

 1 #coding:utf-8 2 ‘‘‘ 3 Created on 2015年8月10日 4  5 @author: yj 6 ‘‘‘ 7 import sys 8 def  skip_header(r): 9     ‘‘‘Skip the reader in reader r,and return the first real piece of data.‘‘‘10     #Read the description line and then the comment lines.讀取描述和注釋行11     line =r.readline()12     print line13     while line.startswith(‘#‘):14         line=r.readline()    #跳到下一行15     #Now line contains the first raal piece of data.16     return line 17 def process_file(r):18     ‘‘‘Read and print open reader r.‘‘‘19     #Find and print piece of data.20     line=skip_header(r).strip()21     print line22     #Read the rest of the data.23     for line in r:24         line=line.strip()25         print line26 if __name__=="__main__":27     print "start"28     input_file=open(sys.argv[1],‘r‘)29     process_file(input_file)30     input_file.close()

 

 

 3、上面的例子用到了一個函數startswith()

函數:startswith()

作用:判斷字串是否以指定字元或子字串開頭

一、函數說明
文法:string.startswith(str, beg=0,end=len(string))
      或string[beg:end].startswith(str)
 
參數說明:
string:  被檢測的字串
str:      指定的字元或者子字串。(可以使用元組,會逐一匹配)
beg:    設定字串檢測的起始位置(可選)
end:    設定字串檢測的結束位置(可選)
如果存在參數 beg 和 end,則在指定範圍內檢查,否則在整個字串中檢查

傳回值
如果檢測到字串,則返回True,否則返回False。預設Null 字元為True

函數解析:如果字串string是以str開始,則返回True,否則返回False

 

執行個體:

s = ‘hello good boy doiido‘print s.startswith(‘h‘)print s.startswith(‘hel‘)print s.startswith(‘h‘,4)print s.startswith(‘go‘,6,8)#匹配Null 字元集print s.startswith(‘‘)#匹配元組print s.startswith((‘t‘,‘b‘,‘h‘))常用環境:用於if判斷if s.startswith(‘hel‘):    print "you are right"else:    print "you are wrang"

 

4、上面的程式用到了strip()函數下面簡單介紹一下

注意:strip()函數本身並不影響原來字串的內容,得到的僅僅是一個新的字串,與原來的字串無關

函數原型

聲明:s為字串,rm為要刪除的字元序列

s.strip(rm)        刪除s字串中開頭、結尾處,位於 rm刪除序列的字元

s.lstrip(rm)       刪除s字串中開頭處,位於 rm刪除序列的字元

s.rstrip(rm)      刪除s字串中結尾處,位於 rm刪除序列的字元

注意:

a. rm為空白時,預設刪除空白符(包括‘\n‘, ‘\r‘,  ‘\t‘,  ‘ ‘)

例如:

複製代碼 代碼如下:

>>> a = ‘     123‘
>>> a.strip()
‘123‘
>>> a=‘\t\tabc‘
‘abc‘
>>> a = ‘sdff\r\n‘
>>> a.strip()
‘sdff‘ 

b.這裡的rm刪除序列是只要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。

例如 : 

複製代碼 代碼如下:

>>> a = ‘123abc‘
>>> a.strip(‘21‘)
‘3abc‘   結果是一樣的
>>> a.strip(‘12‘)
‘3abc‘

 5、函數split()

說明:
Python中沒有字元類型的說法,只有字串,這裡所說的字元就是只包含一個字元的字串!!!
這裡這樣寫的原因只是為了方便理解,僅此而已。

a、按照某個字元分割如“."

1 str = ‘www.baidu.com‘2 #這裡的str.split(‘.‘)的到的是新的字串,並不影響原來的str字串3 str1 = str.split(‘.‘)4 5 print str16 print str7 8 #結果為[‘www‘,‘baidu‘,‘com‘]   ‘www.baidu.com‘

b、按某一個字元分割,且分割n次。如按‘.’分割1次

1 str = (‘www.google.com‘)2 print str3 str_split = str.split(‘.‘,1)4 print str_split5 #結果:[‘www‘,‘google.com‘]

c、按某一字元(或字串)分割,且分割n次,並將分割的完成的字串(或字元)賦給新的(n+1)個變數。(註:見開頭說明)

如:按‘.’分割字元,且分割1次,並將分割後的字串分別賦給2個變數str1,str2

1 url = (‘www.google.com‘)2 str1, str2 = url.split(‘.‘, 1)3 print str14 print str25 6 #結果為:str1:www str2:google.com

 

Python命令列參數sys.argv[]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.