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

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 也都可以被重定向到多个地址,举一反三的事情就自己动手实践吧

时间: 2024-08-06 10:43:05

Python的sys.stdout、sys.stdin重定向的相关文章

python print · sys.stdout · sys.stderr

参考文档 Python重定向标准输入.标准输出和标准错误 http://blog.csdn.net/lanbing510/article/details/8487997 python重定向sys.stdin.sys.stdout和sys.stderr http://www.cnblogs.com/guyuyuan/p/6885448.html 1.print print obj 事实上是调用了sys.stdout.write(obj+'\n'),注意多了一个换行符 1a. print在pytho

Python 标准输出 sys.stdout 重定向

使用 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

python的sys.stdout重定向

一些背景 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(

【Python模块学习】sys模块

sys模块的操作如下: 1 sys.argv # 实现从程序外部向程序传递参数. 2 sys.exit([arg]) # 程序中间的退出,arg=0为正常退出. 3 sys.getdefaultencoding() # 获取系统当前编码,一般默认为ascii. 4 sys.setdefaultencoding() # 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),在执行 setdefaultencoding('utf8'),此时

Python中 os 与 sys 模块

<span style="font-size:18px;">os和sys模块 python常见模块命令 一.OS Python的标准库中的OS模块主要涉及普遍的操作系统功能.可以在Linux和Windows下运行,与平台无关. os.sep 可以取代操作系统特定的路径分割符. os.name字符串指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'. os.getcwd()函数得到当前工作目录,即当前Python脚本

python 基础 7.6 sys 模块

一.sys 模块 sys 模块主要功能是获取参数 [[email protected] pythonscripts]# cat 2.py #!/usr/bin/python #coding=utf-8 import os import sys if  __name__ == '__main__': print ('sys.argv[0]= {0}'.format(sys.argv[0])) print ('sys.argv[1]= {0}'.format(sys.argv[1])) print

Python中os与sys两模块的区别

转载文章 os与sys模块的官方解释如下: os: This module provides a portable way of using operating system dependent functionality. 这个模块提供了一种方便的使用操作系统函数的方法. sys: This module provides access to some variables used or maintained by the interpreter and to functions that i

Python 基础 - 模块 Module - sys模块

sys模块常见函 sys.argv: 实现从程序外部向程序传递参数. sys.exit([arg]): 程序中间的退出,arg=0为正常退出. sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii. sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),在执行 setdefaultencoding('utf8'),此时将系统默认编码设置为utf8.

Python中os和sys模块

系统相关的信息模块: import sys sys.argv 是一个 list,包含所有的命令行参数. sys.stdout sys.stdin sys.stderr 分别表示标准输入输出,错误输出的文件对象. sys.stdin.readline() 从标准输入读一行 sys.stdout.write("a") 屏幕输出a sys.exit(exit_code) 退出程序 sys.modules 是一个dictionary,表示系统中所有可用的module sys.platform