Python的sys.stdout、sys.stdin重定向

转自:http://www.cnblogs.com/turtle-fly/p/3280519.html

本文环境: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 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、sys.stdin重定向相关推荐

  1. sys.stdout sys.stderr的用法

    stdout:标准输出 stderr:标准错误 print  相当于 sys.stdout.write() + 换行 一个将数据流写入文件的程序,文件名为:main.py def main(out=s ...

  2. Python sys.stdout sys.stdin

    引用自:https://www.cnblogs.com/keye/p/7859181.html 引用自:https://blog.csdn.net/sxingming/article/details/ ...

  3. python stdout用法_python学习之 sys.stdout和print

    转自:http://blog.csdn.net/wuxiushu/article/details/52358172 sys.stdout 与print 当我们在 Python 中打印对象调用print ...

  4. python sys stdout_如何理解python中的sys.stdout和sys.stderr

    我有以下简单的python代码. stdout = sys.stdout stderr = sys.stderr try: # omited finally: sys.stdout = stdout ...

  5. python 基础 7.6 sys 模块

    一.sys 模块 sys 模块主要功能是获取参数 [root@www pythonscripts]# cat 2.py #!/usr/bin/python #coding=utf-8 import o ...

  6. Python中os与sys两模块的区别

    <os和sys的官方解释> ➤os os: This module provides a portable way of using operating system dependent ...

  7. python stdout_将stdout重定向到Python中的文件?

    from contextlib import redirect_stdoutwith open('help.txt', 'w') as f: with redirect_stdout(f): prin ...

  8. python stdout stderr_使用Python将stdout和stderr重定向到同一文件

    我想将Python脚本的标准错误和标准输出重定向到同一输出文件.从终端我可以使用 $python myfile.py &> out.txt 来完成我想要的任务,但是我需要从Python脚 ...

  9. python中sys.stdout、sys.stdin

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

最新文章

  1. Unity中的淡入淡出效果
  2. TypeError: unhashable type: 'dict'
  3. matlab学习日记,MATLAB学习笔记---DAY1
  4. 白话经典算法系列之一 冒泡排序的三种实现
  5. mac 删除php56 安装php72,mac php56升级php70
  6. 一起学习linux之lamp脚本
  7. php的SAPI,CLI SAPI,CGI SAPI
  8. python mysql 连接超时时间_一段时间后MySQL连接超时(Python、MySQL、FLASK)
  9. db2 java驱动下载_IBM DB2 jdbc驱动
  10. mysql高频面试题合集
  11. 计算机应用技术个人研修总结,信息技术应用研修总结
  12. 3d胆码计算机方法,3D选胆码方法公式汇总(近88期数据)
  13. Java 开发微信公众号(订阅号)
  14. php框架laravel win10,composer 安装Laravel (win10)
  15. SimpleBGC三轴云台用户手册
  16. 小程序开发 - 基本组件
  17. [ROM制作教程] 【自制ROM工具大集合】各种修改制作ROM工具软件详解以及运用全集合
  18. 一带一红网红基地推出O2O网红直播过年模式
  19. 1.7 ThreadLocal的原理和使用详解
  20. 微信小程序实现顶部导航栏渐变

热门文章

  1. set trans 必须是事务处理的第一个语句_MySQL中特别实用的几种SQL语句送给大家
  2. computed怎么使用_Vuex 基本使用
  3. 怎么能把看不清的照片给看清_远视怎么矫正?需要佩戴眼镜吗?
  4. 工业交换机防护等级介绍
  5. 安防专用交换机的应用介绍
  6. 怪物猎人服务器维护时间,怪物猎人云服务器
  7. 计算机上播放时没声音什么故障,事实:在笔记本电脑上播放歌曲时如果没有声音怎么办...
  8. settimeout怎么用_怎么实现一个3d翻书效果
  9. Java集合(6)--Map接口
  10. 存储限制_明年6月份开始,谷歌相册将终止免费无限存储服务