我可以将python中的stdout重定向到某种字符串缓冲区吗?我用蟒蛇的ftplib编写一个小型FTP客户端,但是包中的一些函数不返回字符串输出,而是打印到stdout..我想重定向stdout可以读取输出的对象。我知道呀stdout可以将以下内容重定向到任何常规文件中:stdout = open("file", "a")但我更喜欢不使用本地驱动器的方法。我在找像BufferedReader在Java中,可以用来将缓冲区包装到流中。
3 回答

慕桂英4014372
TA贡献1871条经验 获得超13个赞
from cStringIO import StringIO # Python3 use: from io import StringIOimport sys old_stdout = sys.stdout sys.stdout = mystdout = StringIO()# blah blah lots of code ...sys.stdout = old_stdout# examine mystdout.getvalue()

慕桂英546537
TA贡献1848条经验 获得超10个赞
import iofrom contextlib import redirect_stdoutwith io.StringIO() as buf, redirect_stdout(buf): print('redirected') output = buf.getvalue()
添加回答
举报
0/150
提交
取消