您的位置:首頁技術文章
文章詳情頁

通過代碼實例了解Python sys模塊

瀏覽:76日期:2022-07-11 11:07:52

sys-系統特定的參數和功能

該模塊提供對解釋器使用或維護的一些變量的訪問,以及與解釋器強烈交互的函數。它始終可用。

代碼如下

#!/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[]列表中總是至少有一個項目,它就是當前運行的程序的名稱,其他的命令行參數在這個項目之后。

另外,sys模塊中還有其他特別有用的項目,sys.stdin sys.stdout sys.stderr分別對應標準輸入、標準輸出、標準錯誤。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区