Python sys.\uu stdout\uuuu工作,但sys.stdout不工作
有一个名为redirect的函数,它临时将文件Python sys.\uu stdout\uuuu工作,但sys.stdout不工作,python,python-2.7,python-3.x,stdout,nosetests,Python,Python 2.7,Python 3.x,Stdout,Nosetests,有一个名为redirect的函数,它临时将文件源上的操作重定向到文件目标 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 fin
源
上的操作重定向到文件目标
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.\uu stdout\uuu
替换sys.stdout
时,没有出现这样的错误,测试成功通过
现在我真的很困惑,为什么
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我通常做的是临时更改我的标准输出
@contextmanager
def replace_stdout(replacement):
_stdout = sys.stdout
sys.stdout = replacement
try:
yield
finally:
sys.stdout = _stdout
并将该上下文管理器用于:
with tempfile.TemporaryFile() as tmp:
with replace_stdout(sys.stdout, tmp):
这种用法与初始标准输出是否有FD无关。您是从空闲环境中运行程序,还是从其他IDE运行程序?我想如果你从系统命令行运行你的程序,你会得到一个实际的sys.stdout
文件。我在terminalAh运行nosetests,是的,nosetests的实现可能会用StringIO
对象替换sys.stdout
,这样它就可以轻松地捕获输出。听起来,nosetests与您试图在其下运行的函数不兼容。似乎nosetests
提供了一个选项<代码>鼻测试-s
工作相关: