我正在使用python ftplib来编写一个小的FTP客户端,但是包中的一些函数不返回字符串输出,而是打印到stdout.我想重定向stdout到一个对象,我将能够从中读取输出.
我知道stdout可以重定向到任何常规文件:
stdout = open("file", "a")
Run Code Online (Sandbox Code Playgroud)
但我更喜欢不使用本地驱动器的方法.
我正在寻找类似于BufferedReaderJava的东西,可用于将缓冲区包装到流中.
在我的python程序开始时,我有以下行:
sys.stdout = open('stdout_file', 'w')
Run Code Online (Sandbox Code Playgroud)
在我的程序中途,我想将stdout设置回正常的标准输出.我该怎么做呢?
已经有一个问题可以回答如何在此处sys.stdout和sys.stderr此处执行此操作: /sf/answers/993795561/
但这并不适用于所有地方。日志模块似乎输出到sys.stdout和sys.stderr,但我无法使用上面的上下文管理器捕获它。
在下面的示例代码中,我试图捕获上下文管理器内的所有输出,但未能为 logger 语句执行此操作:
from __future__ import print_function
import contextlib
import sys
import logging
from StringIO import StringIO
# taken from /sf/answers/993795561/
@contextlib.contextmanager
def stdout_redirect(where):
prev_stdout = sys.stdout
prev_stderr = sys.stderr
prev_stdout.flush()
sys.stdout = where
sys.stderr = where
try:
yield where
finally:
where.flush()
sys.stdout = prev_stdout
sys.stderr = prev_stderr
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
print("\t\tOUTSIDE: stdout", file=sys.stdout)
print("\t\tOUTSIDE: stderr", file=sys.stderr)
logger.info("\tOUTSIDE: info")
logger.debug("\tOUTSIDE: debug")
logger.warn("\tOUTSIDE: warn")
logger.error("\tOUTSIDE: error")
logger.critical("\tOUTSIDE: critical")
print("=============== …Run Code Online (Sandbox Code Playgroud) 是否可以在(交互式)IPython会话中通过stdout寻呼机传递输出,如less?如果是这样,怎么样?
例如,在
In [1]: from some_module import function_that_prints_a_lot
In [2]: function_that_prints_a_lot()
... everything scrolls away ...
Run Code Online (Sandbox Code Playgroud)
我想翻阅stdout输出function_that_prints_a_lot.
另一个例子:
In [1]: %run script_that_prints_a_lot.py
Run Code Online (Sandbox Code Playgroud)
我查看了IPython 魔术命令,但没有找到任何解决方案.