暂时重定向 stdout/stderr

发布于 2024-11-26 10:39:41 字数 221 浏览 0 评论 0原文

是否可以在Python中临时重定向stdout/stderr(即在方法期间)?

编辑:

当前解决方案的问题(我一开始记得但后来忘记了)是它们不重定向;相反,它们只是完全替换了流。因此,如果一个方法出于任何原因(例如,因为流作为参数传递给某个东西)而具有一个变量的本地副本,则该方法将不起作用。

有什么解决办法吗?

Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)?

Edit:

The problem with the current solutions (which I at first remembered but then forgot) is that they don't redirect; rather, they just replace the streams in their entirety. Hence, if a method has a local copy of one the variable for any reason (e.g. because the stream was passed as a parameter to something), it won't work.

Any solutions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

花伊自在美 2024-12-03 10:39:41

您还可以将重定向逻辑放在上下文管理器中。

import os
import sys

class RedirectStdStreams(object):
    def __init__(self, stdout=None, stderr=None):
        self._stdout = stdout or sys.stdout
        self._stderr = stderr or sys.stderr

    def __enter__(self):
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush(); self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, exc_type, exc_value, traceback):
        self._stdout.flush(); self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

if __name__ == '__main__':

    devnull = open(os.devnull, 'w')
    print('Fubar')

    with RedirectStdStreams(stdout=devnull, stderr=devnull):
        print("You'll never see me")

    print("I'm back!")

You can also put the redirection logic in a contextmanager.

import os
import sys

class RedirectStdStreams(object):
    def __init__(self, stdout=None, stderr=None):
        self._stdout = stdout or sys.stdout
        self._stderr = stderr or sys.stderr

    def __enter__(self):
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush(); self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, exc_type, exc_value, traceback):
        self._stdout.flush(); self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

if __name__ == '__main__':

    devnull = open(os.devnull, 'w')
    print('Fubar')

    with RedirectStdStreams(stdout=devnull, stderr=devnull):
        print("You'll never see me")

    print("I'm back!")
怎樣才叫好 2024-12-03 10:39:41

从 python 3.4 开始,有上下文管理器 contextlib .redirect_stdout

from contextlib import redirect_stdout

with open('yourfile.txt', 'w') as f:
    with redirect_stdout(f):
        # do stuff...

要完全静音stdout,此方法有效:

from contextlib import redirect_stdout

with redirect_stdout(None):
    # do stuff...

starting from python 3.4 there is the context manager contextlib.redirect_stdout:

from contextlib import redirect_stdout

with open('yourfile.txt', 'w') as f:
    with redirect_stdout(f):
        # do stuff...

to completely silence stdout this works:

from contextlib import redirect_stdout

with redirect_stdout(None):
    # do stuff...
楠木可依 2024-12-03 10:39:41

要解决某些函数可能已将 sys.stdout 流缓存为局部变量并因此替换全局 sys.stdout 无法在该函数内工作的问题,您可以在文件描述符级别重定向(sys.stdout.fileno()),例如:

from __future__ import print_function
import os
import sys

def some_function_with_cached_sys_stdout(stdout=sys.stdout):
    print('cached stdout', file=stdout)

with stdout_redirected(to=os.devnull), merged_stderr_stdout():
    print('stdout goes to devnull')
    some_function_with_cached_sys_stdout()
    print('stderr also goes to stdout that goes to devnull', file=sys.stderr)
print('stdout is back')
some_function_with_cached_sys_stdout()
print('stderr is back', file=sys.stderr)

stdout_redirected() 重定向 sys.stdout.fileno() 的所有输出给定的文件名、文件对象或文件描述符(示例中的os.devnull)。

stdout_redirected()merged_stderr_stdout() 在此定义

To solve the issue that some function might have cached sys.stdout stream as a local variable and therefore replacing the global sys.stdout won't work inside that function, you could redirect at a file descriptor level (sys.stdout.fileno()) e.g.:

from __future__ import print_function
import os
import sys

def some_function_with_cached_sys_stdout(stdout=sys.stdout):
    print('cached stdout', file=stdout)

with stdout_redirected(to=os.devnull), merged_stderr_stdout():
    print('stdout goes to devnull')
    some_function_with_cached_sys_stdout()
    print('stderr also goes to stdout that goes to devnull', file=sys.stderr)
print('stdout is back')
some_function_with_cached_sys_stdout()
print('stderr is back', file=sys.stderr)

stdout_redirected() redirects all output for sys.stdout.fileno() to a given filename, file object, or file descriptor (os.devnull in the example).

stdout_redirected() and merged_stderr_stdout() are defined here.

允世 2024-12-03 10:39:41

我不确定临时重定向是什么意思。但是,您可以像这样重新分配流并将其重置回来。

temp = sys.stdout
sys.stdout = sys.stderr
sys.stderr = temp

还可以像这样在 print stmts 中写入 sys.stderr 。

 print >> sys.stderr, "Error in atexit._run_exitfuncs:"

常规打印将输出到标准输出。

I am not sure what temporary redirection means. But, you can reassign streams like this and reset it back.

temp = sys.stdout
sys.stdout = sys.stderr
sys.stderr = temp

Also to write to sys.stderr within print stmts like this.

 print >> sys.stderr, "Error in atexit._run_exitfuncs:"

Regular print will to stdout.

眼眸 2024-12-03 10:39:41

可以使用如下所示的装饰器:

import sys

def redirect_stderr_stdout(stderr=sys.stderr, stdout=sys.stdout):
    def wrap(f):
        def newf(*args, **kwargs):
            old_stderr, old_stdout = sys.stderr, sys.stdout
            sys.stderr = stderr
            sys.stdout = stdout
            try:
                return f(*args, **kwargs)
            finally:
                sys.stderr, sys.stdout = old_stderr, old_stdout

        return newf
    return wrap

使用 as:

@redirect_stderr_stdout(some_logging_stream, the_console):
def fun(...):
    # whatever

或者,如果您不想修改 fun 的源代码,请直接将其调用为

redirect_stderr_stdout(some_logging_stream, the_console)(fun)

但请注意,这不是线程安全的。

It's possible with a decorator such as the following:

import sys

def redirect_stderr_stdout(stderr=sys.stderr, stdout=sys.stdout):
    def wrap(f):
        def newf(*args, **kwargs):
            old_stderr, old_stdout = sys.stderr, sys.stdout
            sys.stderr = stderr
            sys.stdout = stdout
            try:
                return f(*args, **kwargs)
            finally:
                sys.stderr, sys.stdout = old_stderr, old_stdout

        return newf
    return wrap

Use as:

@redirect_stderr_stdout(some_logging_stream, the_console):
def fun(...):
    # whatever

or, if you don't want to modify the source for fun, call it directly as

redirect_stderr_stdout(some_logging_stream, the_console)(fun)

But note that this is not thread-safe.

伴梦长久 2024-12-03 10:39:41

这是我发现很有用的上下文管理器。这样做的好处是您可以将它与 with 语句一起使用,并且它还可以处理子进程的重定向。

import contextlib


@contextlib.contextmanager
def stdchannel_redirected(stdchannel, dest_filename):
    """
    A context manager to temporarily redirect stdout or stderr

    e.g.:

    with stdchannel_redirected(sys.stderr, os.devnull):
        ...
    """

    try:
        oldstdchannel = os.dup(stdchannel.fileno())
        dest_file = open(dest_filename, 'w')
        os.dup2(dest_file.fileno(), stdchannel.fileno())

        yield
    finally:
        if oldstdchannel is not None:
            os.dup2(oldstdchannel, stdchannel.fileno())
        if dest_file is not None:
            dest_file.close()

我创建此内容的上下文位于 这篇博文

Here's a context manager that I found useful. The nice things about this are that you can use it with the with statement and it also handles redirecting for child processes.

import contextlib


@contextlib.contextmanager
def stdchannel_redirected(stdchannel, dest_filename):
    """
    A context manager to temporarily redirect stdout or stderr

    e.g.:

    with stdchannel_redirected(sys.stderr, os.devnull):
        ...
    """

    try:
        oldstdchannel = os.dup(stdchannel.fileno())
        dest_file = open(dest_filename, 'w')
        os.dup2(dest_file.fileno(), stdchannel.fileno())

        yield
    finally:
        if oldstdchannel is not None:
            os.dup2(oldstdchannel, stdchannel.fileno())
        if dest_file is not None:
            dest_file.close()

The context for why I created this is at this blog post.

写给空气的情书 2024-12-03 10:39:41

Raymond Hettinger 向我们展示了一种更好的方法[1]:

import sys
with open(filepath + filename, "w") as f: #replace filepath & filename
    with f as sys.stdout:
        print("print this to file")   #will be written to filename & -path

在 with 块之后,sys.stdout 将被重置

[1 ]: <一href="http://www.youtube.com/watch?v=OSGv2VnC0go&list=PLQZM27HgcgT-6D0w6arhnGdSHDcSmQ8r3" rel="nofollow noreferrer">http://www.youtube.com/watch?v=OSGv2VnC0go&list=PLQZM27HgcgT-6D0w6arhnGdSHDcSmQ8r3

Raymond Hettinger shows us a better way[1]:

import sys
with open(filepath + filename, "w") as f: #replace filepath & filename
    with f as sys.stdout:
        print("print this to file")   #will be written to filename & -path

After the with block the sys.stdout will be reset

[1]: http://www.youtube.com/watch?v=OSGv2VnC0go&list=PLQZM27HgcgT-6D0w6arhnGdSHDcSmQ8r3

不寐倦长更 2024-12-03 10:39:41

查看 contextlib.redirect_stdout(new_target)contextlib.redirect_stderr(new_target)redirect_stderr 是 Python 3.5 中的新增功能。

Look at contextlib.redirect_stdout(new_target) and contextlib.redirect_stderr(new_target). redirect_stderr is new in Python 3.5.

若有似无的小暗淡 2024-12-03 10:39:41

我们将使用 ob_startPHP 语法python3中的a>和ob_get_contents函数,并重定向输入到一个文件中。

输出存储在文件中,也可以使用任何类型的流。

from functools import partial
output_buffer = None
print_orig = print
def ob_start(fname="print.txt"):
    global print
    global output_buffer
    print = partial(print_orig, file=output_buffer)
    output_buffer = open(fname, 'w')
def ob_end():
    global output_buffer
    close(output_buffer)
    print = print_orig
def ob_get_contents(fname="print.txt"):
    return open(fname, 'r').read()

用途:

print ("Hi John")
ob_start()
print ("Hi John")
ob_end()
print (ob_get_contents().replace("Hi", "Bye"))

打印

嗨约翰
再见约翰

We'll use the PHP syntax of ob_start and ob_get_contents functions in python3, and redirect the input into a file.

The outputs are being stored in a file, any type of stream could be used as well.

from functools import partial
output_buffer = None
print_orig = print
def ob_start(fname="print.txt"):
    global print
    global output_buffer
    print = partial(print_orig, file=output_buffer)
    output_buffer = open(fname, 'w')
def ob_end():
    global output_buffer
    close(output_buffer)
    print = print_orig
def ob_get_contents(fname="print.txt"):
    return open(fname, 'r').read()

Usage:

print ("Hi John")
ob_start()
print ("Hi John")
ob_end()
print (ob_get_contents().replace("Hi", "Bye"))

Would print

Hi John
Bye John

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文