【发布时间】:2015-06-21 04:07:22
【问题描述】:
有一个名为redirect的函数,它临时将文件source上的操作重定向到文件target。
def redirect(source, target):
source.flush()
fd = source.fileno()
with os.fdopen(os.dup(fd), source.mode) as source2:
os.dup2(target.fileno(), fd)
try:
yield
finally:
source.flush()
os.dup2(source2.fileno(), fd)
它是从同一个模块调用的
with tempfile.TemporaryFile() as tmp:
with redirect(sys.stdout, tmp), nogil:
编译的时候会产生一个AttributeError
AttributeError: StringIO instance has no attribute 'fileno'
在线fd = source.fileno()。
但是当我把sys.stdout换成sys.__stdout__后,就没有这个错误了,测试成功了。
现在我真的很困惑,为什么 __stdout__ 有效但 stdout 无效。
【问题讨论】:
-
您是在 IDLE 环境中运行程序,还是从另一个 IDE 运行程序?我想如果你从系统命令行运行你的程序,你会得到一个
sys.stdout的实际文件。 -
我正在从终端运行鼻子测试
-
啊,是的,nosetests 的实现可能将
sys.stdout替换为StringIO对象,以便它可以轻松捕获输出。听起来鼻子测试与您尝试在其下运行的功能不兼容。 -
看来
nosetests为此提供了一个选项。nosetests -s工作。
标签: python python-2.7 python-3.x stdout nosetests