我正在使用python的ftplib编写一个小的FTP客户端,但是包中的一些函数并不返回字符串输出,而是打印到stdout。我想将stdout重定向到一个我可以从中读取输出的对象。
我知道可以使用以下命令将stdout重定向到任何常规文件:
stdout = open("file", "a")但我更喜欢不使用本地驱动器的方法。
我正在寻找类似于Java中的BufferedReader的东西,它可以用来将缓冲区包装到流中。
发布于 2009-08-02 13:57:42
from cStringIO import StringIO # Python3 use: from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
sys.stdout = old_stdout
# examine mystdout.getvalue()发布于 2014-03-16 16:18:23
Python 3.4+中有一个contextlib.redirect_stdout() function:
import io
from contextlib import redirect_stdout
with io.StringIO() as buf, redirect_stdout(buf):
print('redirected')
output = buf.getvalue()这是一个code example that shows how to implement it on older Python versions。
发布于 2017-08-27 05:45:56
Python3的上下文管理器:
import sys
from io import StringIO
class RedirectedStdout:
def __init__(self):
self._stdout = None
self._string_io = None
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._string_io = StringIO()
return self
def __exit__(self, type, value, traceback):
sys.stdout = self._stdout
def __str__(self):
return self._string_io.getvalue()像这样使用:
>>> with RedirectedStdout() as out:
>>> print('asdf')
>>> s = str(out)
>>> print('bsdf')
>>> print(s, out)
'asdf\n' 'asdf\nbsdf\n'https://stackoverflow.com/questions/1218933
复制相似问题