4 回答
TA贡献1752条经验 获得超4个赞
contextlib.redirect_stdout()
from contextlib import redirect_stdoutwith open('help.txt', 'w') as f: with redirect_stdout(f): print('it now prints to `help.text`')
import sysfrom contextlib import contextmanager@contextmanagerdef redirect_stdout(new_target): old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout try: yield new_target # run some code with the replaced stdout finally: sys.stdout = old_target # restore to the previous value
import osfrom contextlib import redirect_stdout stdout_fd = sys.stdout.fileno()with open('output.txt', 'w') as f, redirect_stdout(f): print('redirected to a file') os.write(stdout_fd, b'not redirected') os.system('echo this also is not redirected')
b'not redirected'
'echo this also is not redirected'
output.txt
os.dup2()
import osimport sysfrom contextlib import contextmanagerdef fileno(file_or_fd): fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd@contextmanagerdef stdout_redirected(to=os.devnull, stdout=None): if stdout is None: stdout = sys.stdout stdout_fd = fileno(stdout) # copy stdout_fd before it is overwritten #NOTE: `copied` is inheritable on Windows when duplicating a standard stream with os.fdopen(os.dup(stdout_fd), 'wb') as copied: stdout.flush() # flush library buffers that dup2 knows nothing about try: os.dup2(fileno(to), stdout_fd) # $ exec >&to except ValueError: # filename with open(to, 'wb') as to_file: os.dup2(to_file.fileno(), stdout_fd) # $ exec > to try: yield stdout # allow code to be run with the redirected stdout finally: # restore stdout to its previous value #NOTE: dup2 makes stdout_fd inheritable unconditionally stdout.flush() os.dup2(copied.fileno(), stdout_fd) # $ exec >&copied
stdout_redirected()
redirect_stdout()
:
import osimport sys stdout_fd = sys.stdout.fileno()with open('output.txt', 'w') as f, stdout_redirected(f): print('redirected to a file') os.write(stdout_fd, b'it is redirected now\n') os.system('echo this is also redirected')print('this is goes back to stdout')
output.txt
stdout_redirected()
stdout.flush()
read()
/write()
libc.fflush(None)
try: import ctypes from ctypes.util import find_libraryexcept ImportError: libc = Noneelse: try: libc = ctypes.cdll.msvcrt # Windows except OSError: libc = ctypes.cdll.LoadLibrary(find_library('c'))def flush(stream): try: libc.fflush(None) stream.flush() except (AttributeError, ValueError, IOError): pass # unsupported
stdout
sys.stdout
sys.stderr
sys.stdout
:
def merged_stderr_stdout(): # $ exec 2>&1 return stdout_redirected(to=sys.stdout, stdout=sys.stderr)
from __future__ import print_functionimport syswith merged_stderr_stdout(): print('this is printed on stdout') print('this is also printed on stdout', file=sys.stderr)
stdout_redirected()
sys.stdout
python-daemon
logging
print
nohup
TA贡献1906条经验 获得超3个赞
import sysclass Logger(object): def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "a") def write(self, message): self.terminal.write(message) self.log.write(message)sys.stdout = Logger("yourlogfilename.txt")print "Hello world !" # this is should be saved in yourlogfilename.txt
TA贡献1793条经验 获得超6个赞
from os import open, close, dup, O_WRONLY old = dup(1)close(1)open("file", O_WRONLY) # should open on 1..... do stuff and then restore close(1)dup(old) # should dup to 1close(old) # get rid of left overs
添加回答
举报