sys.stdout控制流重定向输出
在Python中,文件对象sys.stdin、sys.stdout和sys.stderr分别对应解释器的标准输入、标准输出和标准出错流。在程序启动时,这些对象的初值由sys.__stdin__、sys.__stdout__和sys.__stderr__保存,以便用于收尾(finalization)时恢复标准流对象。
sys.stdin输入
sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符'\n'的。
因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip('\n'))或sys.stdin.readline( )[:-1]这两种方法去掉换行。
sys.stdout控制台输出
当我们在 Python中打印对象调用 printobj 时候,事实上是调用了 sys.stdout.write(obj+'\n')print将你需要的内容打印到了控制台,然后追加了一个换行符print会调用 sys.stdout 的write 方法
print语句(statement)不以逗号结尾时,会在输出字符串尾部自动附加一个换行符(linefeed);否则将一个空格代替附加的换行符。print语句默认写入标准输出流,也可重定向至文件或其他可写对象(所有提供write方法的对象)。这样,就可以使用简洁的print语句代替笨拙的object.write('hello'+'\n')写法。
由上可知,在Python中调用print obj打印对象时,缺省情况下等效于调用sys.stdout.write(obj+'\n')
import sys
sys.write("233"+"\n")
print("666")
sys.stdout重定向输出
将一个可写对象(如file-like对象)赋给sys.stdout,可使随后的print语句输出至该对象。重定向结束后,应将sys.stdout恢复最初的缺省值,即标准输出。
1)
import sys
savedStdout = sys.stdout #保存标准输出流
with open('out.txt', 'w+') as file:
sys.stdout = file #标准输出重定向至文件
print 'This message is for file!'
sys.stdout = savedStdout #恢复标准输出流
# sys.stdout = sys.__stdout__ # 恢复标准输出流
print 'This message is for screen!'
2)
import io
import sys
if sys.platform.startswith("win"):
def console(char, background):
return char or " "
sys.stdout = io.StringIO()
print(object)
with open("test.txt","w",encoding="utf-8") as f:
f.write(sys.stdout.getvalue())
控制输出类
import os
import sys
import io
class RedirectStdout:
def __init__(self):
self.content = '' #保存输出文本
self.savedStdout = sys.stdout #保存输出模式
self.memObj, self.fileObj, self.nulObj = None, None, None
# 外部的print语句将执行本write()方法,并由当前sys.stdout输出
def write(self, outStr):
# self.content.append(outStr)
self.content += outStr
def toCons(self): # 标准输出重定向至控制台
sys.stdout = self.savedStdout # sys.__stdout__
def toMemo(self): # 标准输出重定向至内存
self.memObj = io.StringIO()
sys.stdout = self.memObj
def toFile(self, file='out.txt'): # 标准输出重定向至文件
self.fileObj = open(file, 'a+', 1) # 改为行缓冲
sys.stdout = self.fileObj
def toMute(self): # 抑制输出
self.nulObj = open(os.devnull, 'w')
sys.stdout = self.nulObj
def restore(self): #重置状态
self.content = ''
if self.memObj.closed != True:
self.memObj.close()
if self.fileObj.closed != True:
self.fileObj.close()
if self.nulObj.closed != True:
self.nulObj.close()
sys.stdout = self.savedStdout # sys.__stdout__
测试
redirObj = RedirectStdout()
sys.stdout = redirObj # 本句会抑制"Let's begin!"输出
print("Let's begin!")
# 屏显'Hello World!'和'I am xywang.'(两行)
redirObj.toCons()
print('Hello World!')
print('I am xywang.')
# 写入'How are you?'和"Can't complain."(两行)
redirObj.toFile()
print('How are you?')
print("Can't complain.")
# 抑制输出
redirObj.toMute()
print('<Silence>') # 无屏显或写入
os.system('echo Never redirect me!') # 控制台屏显'Never redirect me!'
# 写入内存
redirObj.toMemo()
print('What a pity!') # 无屏显或写入
with open("test.txt","w",encoding="utf-8") as f:
f.write(sys.stdout.getvalue())
redirObj.toCons()
print('Hello?') # 屏显
# 重置
redirObj.restore()
print('Pop up') # 屏显