通過(guò)代碼實(shí)例了解Python sys模塊
sys-系統(tǒng)特定的參數(shù)和功能
該模塊提供對(duì)解釋器使用或維護(hù)的一些變量的訪問(wèn),以及與解釋器強(qiáng)烈交互的函數(shù)。它始終可用。
代碼如下
#!/usr/bin/python # Filename: cat.py 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': print 'Version 1.2' elif option == '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(filename)
這個(gè)程序用來(lái)模仿linux中的cat命令。
在python程序運(yùn)行的時(shí)候,即不是在交互模式下,在sys.argv[]列表中總是至少有一個(gè)項(xiàng)目,它就是當(dāng)前運(yùn)行的程序的名稱,其他的命令行參數(shù)在這個(gè)項(xiàng)目之后。
另外,sys模塊中還有其他特別有用的項(xiàng)目,sys.stdin sys.stdout sys.stderr分別對(duì)應(yīng)標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯(cuò)誤。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python 中的collections.OrderedDict() 用法
這篇文章主要介紹了python 中的collections.OrderedDict() 用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05python中使用 xlwt 操作excel的常見(jiàn)方法與問(wèn)題
這篇文章主要給大家介紹了關(guān)于python中使用 xlwt 操作excel的常見(jiàn)方法與問(wèn)題的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01Python 限制線程的最大數(shù)量的方法(Semaphore)
今天小編就為大家分享一篇Python 限制線程的最大數(shù)量的方法(Semaphore),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02python matplotlib畫(huà)圖實(shí)例代碼分享
這篇文章主要介紹了python matplotlib畫(huà)圖實(shí)例代碼分享,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12在pycharm中無(wú)法import所安裝的庫(kù)解決方案
這篇文章主要介紹了在pycharm中無(wú)法import所安裝的庫(kù)解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05