本文环境:Python 2.7

使用 print obj 而非 print(obj)

一些背景

sys.stdout 与 print

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')

print 将你需要的内容打印到了控制台,然后追加了一个换行符

print 会调用 sys.stdout 的 write 方法

以下两行在事实上等价:

sys.stdout.write('hello'+'\n')
print 'hello'

sys.stdin 与 raw_input

当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入

以下两组在事实上等价:

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 指向控制台

如果把文件的对象的引用赋给 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 也都可以被重定向到多个地址,举一反三的事情就自己动手实践吧

Python 标准输出 sys.stdout 重定向的更多相关文章

  1. Python 标准输出 sys.stdout 重定向(转)

    add by zhj: 其实很少使用sys.stdout,之前django的manage.py命令的源码中使用了sys.stdout和sys.stderr,所以专门查了一下 这两个命令与print的区 ...

  2. PyQt(Python+Qt)学习随笔:print标准输出sys.stdout以及stderr重定向QTextBrowser等图形界面对象

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 <在Python实现print标准输出sys.stdout.st ...

  3. 在Python实现print标准输出sys.stdout、stderr重定向及捕获的简单办法

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 Python中的标准输出和错误输出由sys模块的stdout.stde ...

  4. python之sys.stdout、sys.stdin以及设置打印到日志文件等

    转自:https://www.cnblogs.com/BigFishFly/p/6622784.html python之sys.stdout.sys.stdin 转自:http://www.cnblo ...

  5. python 中sys.stdout.write 和 print >> sys.stdout的区别(转)

    下面应该可以解你的惑了: print >> sys.stdout的形式就是print的一种默认输出格式,等于print "%VALUE%" 看下面的代码的英文注释,是p ...

  6. python之sys.stdout、sys.stdin

    转自:http://www.cnblogs.com/turtle-fly/p/3280519.html 本文环境:Python 2.7  使用 print obj 而非 print(obj) sys. ...

  7. python中sys.stdout、sys.stdin

    如果需要更好的控制输出,而print不能满足需求,sys.stdout,sys.stdin,sys.stderr就是你需要的. 1. sys.stdout与print: 在python中调用print ...

  8. Python 为什么sys.stdout.write 输出时后面总跟一个数字

    sys.stdout 是标准输出文件.write就是往这个文件写数据. 合起来就是打印数据到标准输出 因为-在交互模式下会输出函数返回值,而write会返回输出的字符数量.在命令行里不会显示

  9. python 之 sys.stdout输出不换行

    在处理程序打进度条时,希望不换行显示进度,可以使用sys.stdout相关函数来进行处理. 1.print 输出不换行 首先可以使用print函数来整体输入,利用,结尾就可以在同一行内显示: # py ...

随机推荐

  1. Linux 常用文件

    /etc/exports /etc/services /etc/sysctl.conf /etc/logrotate.conf /etc/docker/key.json /etc/docker/dae ...

  2. U3D之Editor扩展学习

    Unity3D提供了强大的编辑器扩展机制,在项目开发中,如果可以将一些繁琐的工作放在编辑器扩展中进行,则会大大提高效率.本文对编辑器扩展进行了一些总结,希望对有兴趣编写编辑器扩展的开发人员有所帮助.当 ...

  3. The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make s

    我出现这个问题是引用资源文件问题 helper.getView(R.id.in_pic).setBackgroundResource(item.getResourceId()); //错的helper ...

  4. N76E003的学习之路(ADC简单小例程篇)

    N76E003内嵌12位逐次逼近寄存器型(SAR)的模拟数字转换器(ADC).模数转换模块负责将管脚上的模拟信号转换为12位二进制数据.N76E003支持8通道单端输入模式.内部带隙电压(band-g ...

  5. PowerDesigner学习笔记

    首先是概念模型个物理模型的区别,概念模型,即ConceptualDataMode,是没和具体类型的数据库(如SQL Server.MySql)的对应,是一种抽象的,而物理模型是指定了某种具体类型的数据 ...

  6. 《转载》Linux服务之搭建FTP服务器&&分布式文件服务器的比较

    参考帖子: Linux服务之FTP vsftpd的使用 大型网站图片服务器架构的演进 rsync同步文件的艺术  rsync命令详解 深入理解Tomcat虚拟目录  (测试已经OK)

  7. 原生js--http请求

    1.终止请求和超时 终止请求XMLHttpRequest对象提供abort方法,调用该方法时触发abort事件 XHR2提供了timeout属性,当超时发生时触发timeout事件.但浏览器尚不支持自 ...

  8. windows下php使用protobuf

    1.下载protobufc https://github.com/google/protobuf/releases/download/v3.5.0/protoc-3.5.0-win32.zip解压后放 ...

  9. LeetCode 31 Next Permutation(下一个全排列)

    题目链接: https://leetcode.com/problems/next-permutation/?tab=Description   Problem :寻找给定int数组的下一个全排列(要求 ...

  10. LeetCode 15 3Sum(3个数求和为0的组合)

    题目链接 https://leetcode.com/problems/3sum/?tab=Description   Problem: 给定整数集合,找到所有满足a+b+c=0的元素组合,要求该组合不 ...