python中sys.argv參數用法執行個體分析

來源:互聯網
上載者:User

   本文執行個體講述了python中sys.argv參數用法。分享給大家供大家參考。具體分析如下:

  在學python的過程中,一直弄不明白sys.argv[]的意思,雖知道是表示命令列參數,但還是有些稀裡糊塗的感覺。

  今天又好好學習了一把,總算是大徹大悟了。

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

  1、使用sys.argv[]的一簡單一實例

  ?

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

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

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

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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, # notice comma 分別輸出每行內容 f.close() # 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': #當命令列參數為-- version,顯示版本號碼 print 'Version 1.2' elif option == 'help': #當命令列參數為--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,讀出其內容 readfile(filename)

  儲存程式為sample.py.我們驗證一下:

  命令列帶參數運行:sample.py –version 輸出結果為:version 1.2

  命令列帶參數運行:sample.py –help 輸出結果為:This program prints files……

  在與sample.py同一目錄下,建立a.txt的記事本檔案,內容為:test argv;命令列帶參數運行:sample.py a.txt,輸出結果為a.txt檔案內容:test argv,這裡也可多帶幾個參數,程式會先後輸出參數檔案內容。

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

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