背景:
1.当我们在python中调用print obj时,事实上是调用了sys.stdout.write(obj + ‘\n’)
print 将你需要的内容打印到了控制台,然后加了一个换行符。
2.当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入
以下两组在事实上等价:
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
3.根据背景介绍,我们可以构造一个具有write方法的对象,让他将标准输出重定向,存储到别的位置,如下:
import sys
class __redirection__:
def __init__(self):
self.buff=''
self.__console__=sys.stdout
def write(self, output_stream):
self.buff+=output_stream
def to_console(self):
sys.stdout=self.__console__
print self.buff
def to_file(self, file_path):
f=open(file_path,'w')
sys.stdout=f
print self.buff
f.close()
def flush(self):
self.buff=''
def reset(self):
sys.stdout=self.__console__
if __name__=="__main__":
# redirection
r_obj=__redirection__()
sys.stdout=r_obj
# get output stream
print 'hello'
print 'there'
# redirect to console
r_obj.to_console()
# redirect to file
r_obj.to_file('out.log')
# flush buffer
r_obj.flush()
# reset
r_obj.reset()
文章大部分内容转自:https://www.cnblogs.com/ajianbeyourself/p/6927925.html