Tymczasowe przekierowanie stdout/stderr

Czy jest możliwe tymczasowe przekierowanie stdout/stderr w Pythonie (tzn. na czas trwania metody)?

Edit:

Problem z obecnymi rozwiązaniami (które na początku zapamiętałem, ale potem zapomniałem) polega na tym, że nie przekierowują ; zamiast tego zastępują strumienie w całości. Stąd, jeśli metoda ma local skopiuj jednej zmiennej z dowolnego powodu( np. ponieważ strumień został przekazany jako parametr do czegoś), nie będzie praca.

Jakieś rozwiązania?

Author: Mehrdad, 2011-07-23

9 answers

Aby rozwiązać problem, że niektóre funkcje mogły buforować strumień sys.stdout jako zmienną lokalną i dlatego zastąpienie globalnego sys.stdout nie będzie działać wewnątrz tej funkcji, Możesz przekierować na poziomie deskryptora pliku (sys.stdout.fileno()), np.:

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() przekierowuje wszystkie dane wyjściowe dla sys.stdout.fileno() do podanej nazwy pliku, obiektu pliku lub deskryptora pliku (os.devnull w przykładzie).

stdout_redirected() i merged_stderr_stdout() są zdefiniowane tutaj .

 17
Author: jfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:17:36

Można również umieścić logikę przekierowania w Menedżerze kontekstowym.

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!")
 83
Author: Rob Cowie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-19 09:36:41

Nie jestem pewien, co oznacza tymczasowe przekierowanie. Ale możesz przypisać takie strumienie i zresetować je z powrotem.

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

Również do zapisu do sys.stderr w print stmts w ten sposób.

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

Zwykły druk będzie na stdout.

 16
Author: Senthil Kumaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-22 21:56:37

Jest to możliwe z dekoratorem, takim jak:

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

Użyj jako:

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

Lub, jeśli nie chcesz modyfikować źródła dla fun, wywołaj je bezpośrednio jako

redirect_stderr_stdout(some_logging_stream, the_console)(fun)

Ale zauważ, że nie jest to bezpieczne dla wątków.

 11
Author: Fred Foo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-22 12:05:23

Począwszy od Pythona 3.4 istnieje menedżer kontekstu contextlib.redirect_stdout:

from contextlib import redirect_stdout

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

Aby całkowicie uciszyć stdout to działa:

from contextlib import redirect_stdout

with redirect_stdout(None):
    # do stuff...
 5
Author: hiro protagonist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 06:56:56

Oto menedżer kontekstu, który uważam za przydatny. Fajne w tym jest to, że można go używać z instrukcją with, a także obsługuje przekierowania dla procesów potomnych.

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()

Kontekst dlaczego stworzyłem to jest w ten wpis na blogu .

 4
Author: Marc Abramowitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-19 17:50:08

Raymond Hettinger pokazuje nam lepszy sposób[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

Po z blokuje sys.stdout zostanie zresetowany

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

 1
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:17:36

Użyjemy składni PHP Funkcji ob_start i ob_get_contents w python3 i przekierujemy dane wejściowe do pliku.

Wyjścia są przechowywane w pliku, można również użyć dowolnego strumienia.

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()

Użycie:

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

Drukuje

Cześć John. Bye John
 0
Author: Uri Goren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-14 08:14:55
 0
Author: Cristóbal Ganter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-03 01:29:46