程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> python中sys.argv參數用法實例分析

python中sys.argv參數用法實例分析

編輯:更多關於編程

       本文實例講述了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程序設計有所幫助。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved