通過代碼實例了解Python sys模塊
sys-系統(tǒng)特定的參數(shù)和功能
該模塊提供對解釋器使用或維護的一些變量的訪問,以及與解釋器強烈交互的函數(shù)。它始終可用。
代碼如下
#!/usr/bin/python# Filename: cat.pyimport sysdef 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 hereif 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)
這個程序用來模仿linux中的cat命令。
在python程序運行的時候,即不是在交互模式下,在sys.argv[]列表中總是至少有一個項目,它就是當前運行的程序的名稱,其他的命令行參數(shù)在這個項目之后。
另外,sys模塊中還有其他特別有用的項目,sys.stdin sys.stdout sys.stderr分別對應(yīng)標準輸入、標準輸出、標準錯誤。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Intellij IDEA 2019 最新亂碼問題及解決必殺技(必看篇)2. java實現(xiàn)圖形化界面計算器3. Android 7.0 運行時權(quán)限彈窗問題的解決4. IntelliJ IDEA設(shè)置條件斷點的方法步驟5. 《javascript設(shè)計模式》學(xué)習筆記三:Javascript面向?qū)ο蟪绦蛟O(shè)計單例模式原理與實現(xiàn)方法分析6. ASP.NET MVC獲取多級類別組合下的產(chǎn)品7. 關(guān)于HTML5的img標簽8. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法9. ASP基礎(chǔ)入門第七篇(ASP內(nèi)建對象Response)10. 原生js XMLhttprequest請求onreadystatechange執(zhí)行兩次的解決
