sys-系統特定的參數和功能
該模塊提供對解釋器使用或維護的一些變量的訪問,以及與解釋器強烈交互的函數。它始終可用。
代碼如下
#!/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)
這個程序用來模仿linux中的cat命令。
在python程序運行的時候,即不是在交互模式下,在sys.argv[]列表中總是至少有一個項目,它就是當前運行的程序的名稱,其他的命令行參數在這個項目之后。
另外,sys模塊中還有其他特別有用的項目,sys.stdin sys.stdout sys.stderr分別對應標準輸入、標準輸出、標準錯誤。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。