本文环境:Python 2.7 python
使用 print obj 而非 print(obj)函数
当咱们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')this
print 将你须要的内容打印到了控制台,而后追加了一个换行符spa
print 会调用 sys.stdout 的 write 方法指针
如下两行在事实上等价:日志
sys.stdout.write('hello'+'\n') print 'hello'
当咱们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,而后捕获输入code
如下两组在事实上等价:对象
hi=raw_input('hello? ') print 'hello? ', #comma to stay in the same line hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
原始的 sys.stdout 指向控制台blog
若是把文件的对象的引用赋给 sys.stdout,那么 print 调用的就是文件对象的 write 方法内存
f_handler=open('out.log', 'w') sys.stdout=f_handler print 'hello' # this hello can't be viewed on concole # this hello is in file out.log
记住,若是你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印以后再恢复 sys.stdout
__console__=sys.stdout # redirection start # ... # redirection end sys.stdout=__console__
若是咱们但愿打印的内容一方面输出到控制台,另外一方面输出到文件做为日志保存,那么该怎么办?
将打印的内容保留在内存中,而不是一打印就将 buffer 释放刷新,那么放到一个字符串区域中会怎样?
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()
一样的,sys.stderr, sys.stdin 也均可以被重定向到多个地址,触类旁通的事情就本身动手实践吧