标准输出(sys.stdout)对应的操做就是print(打印)了,标准输入(sys.stdin)则对应input(接收输入)操做,标准错误输出和标准输出相似也是print(打印)。python
python最基本的操做 - 打印:函数
print 1
其效果是把 1 写在console(命令行)里面让你看。命令行
实际上他的操做能够理解为:把console(命令行)做为一个板子,经过sys.stdout = console指定往console板子上写东西(console是默认的,也就是说你不修改要往哪儿写的话,就会默认往这写),在print 1的时候,就是告诉python,我要写1,而后python就会去sys.stdout所指定的板子里,也就是console(命令行)里写上 1。(标准错误输出也是一样的过程,你会发现当程序出错时,错误信息也会打印在console里面。)指针
其实只要一个对象具备write方法,就能够被看成“板子”,告诉sys.stdout去哪里写。日志
说道write方法,第一个想到的可能就是文件操做了。code
f=open('log.txt','w')
像上面那样声明一个文件对象 f,此文件对象就拥有了write方法,就能够被用来看成标准输出和保准错误输出的板子。对象
f=open('log.txt','w') __console__ = sys.stdout #把默认的“板子” - 命令行作个备份,以即可以改回来 sys.stdout = f print 1 sys.stdout = __console__ print 2
上面的操做,经过sys.stdout = f 指定打印时的板子改为了 f。因此在使用print的时候,再也不是把1打印在命令行里,而是写在了log.txt文件里面。后面又把板子改为了命令行,此时print 2就又把2打印到命令行内存
#同时重定向到控制台和文件字符串
若是咱们但愿打印的内容一方面输出到控制台,另外一方面输出到文件做为日志保存,那么该怎么办? 将打印的内容保留在内存中,而不是一打印就将 buffer 释放刷新,那么放到一个字符串区域中会怎样?get
a='' sys.stdout=a print 'hello'
OK,上述代码是没法正常运行的
Traceback (most recent call last): File ".\hello.py", line xx, in <module> print 'hello' AttributeError: 'str' object has no attribute 'write'
错误很明显,就是上面强调过的,在尝试调用 sys.stdout.write() 的时候,发现没有 write 方法
另外,这里之因此提示 attribute error 而不是找不到函数等等,我猜测是由于 python 将对象/类的函数指针记录做为对象/类的一个属性来对待,只是保留了函数的入口地址
既然这样,那么咱们必须给重定向到的对象实现一个 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()