正確掌握Python sys.arg使用方法
在Python編程語言中,有很多比較特殊的應用方法值得我們?nèi)ゼ毤毱肺?。在這里我們將會為大家詳細分析一下有關Python sys.arg使用的方法,希望可以給朋友們帶來一些幫助,以方便在應用中的使用。
Python sys.arg使用是用來獲取命令行參數(shù)的,sys.argv[0]表示代碼本身文件路徑,所以參數(shù)從1開始,以下兩個例子說明:
1、使用sys.argv[]的一簡單實例,
- import sys,os
 - os.system(sys.argv[1])
 - import sys,os
 - os.system(sys.argv[1])
 
這個例子os.system接收命令行參數(shù),運行參數(shù)指令,保存為sample1.py,命令行帶參數(shù)運行sample1.py notepad,將打開記事本程序。
2、這個例子是簡明Python教程上的,明白它之后你就明白Python sys.arg使用了。
- import sys
 - def readfile(filename): #從文件中讀出文件內(nèi)容
 - '''''Print a file to the standard output.'''
 - f = file(filename)
 - while True:
 - line = f.readline()
 - if len(line) == 0:
 - break
 - print line, # notice comma 分別輸出每行內(nèi)容
 - if.close()
 - # Script starts from here
 - if len(sys.argv) < 2:
 - print 'No action specified.'
 - sys.exit()
 - 15if sys.argv[1].startswith('--'):
 - option = sys.argv[1][2:]
 - # fetch sys.argv[1] but without the first two characters
 - if option == 'version': #當命令行參數(shù)為-- version,顯示版本號
 - print 'Version 1.2'
 - elif option == 'help': #當命令行參數(shù)為--help時,顯示相關幫助內(nèi)容
 - 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:]: #當參數(shù)為文件名時,傳入readfile,讀出其內(nèi)容
 - readfile(filename)
 - import sys
 - def readfile(filename): #從文件中讀出文件內(nèi)容
 - '''Print a file to the standard output.'''
 - f = file(filename)
 - while True:
 - line = f.readline()
 - if len(line) == 0:
 - break
 - print line, # notice comma 分別輸出每行內(nèi)容
 - 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': #當命令行參數(shù)為-- version,顯示版本號
 - print 'Version 1.2'
 - elif option == 'help': #當命令行參數(shù)為--help時,顯示相關幫助內(nèi)容
 - 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:]: #當參數(shù)為文件名時,傳入readfile,讀出其內(nèi)容
 - readfile(filename)
 
保存程序為sample.py.我們驗證一下:#t#
< !--[if !supportLists]-->1) < !--[endif]-->命令行帶參數(shù)運行:sample.py –version 輸出結果為:version 1.2
< !--[if !supportLists]-->2) < !--[endif]-->命令行帶參數(shù)運行:sample.py –help 輸出結果為:This program prints files……
< !--[if !supportLists]-->3) < !--[endif]-->在與sample.py同一目錄下,新建a.txt的記事本文件,內(nèi)容為:test argv;命令行帶參數(shù)運行:sample.py a.txt,輸出結果為a.txt文件內(nèi)容:test argv,這里也可以多帶幾個參數(shù),程序會先后輸出參數(shù)文件內(nèi)容。以上就是我們?yōu)榇蠹医榻B的Python sys.arg使用相關方法。















 
 
 


 
 
 
 