Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python sys.\uu stdout\uuuu工作,但sys.stdout不工作_Python_Python 2.7_Python 3.x_Stdout_Nosetests - Fatal编程技术网

Python sys.\uu stdout\uuuu工作,但sys.stdout不工作

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

有一个名为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
        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
工作相关: