python stdout_将stdout重定向到Python中的文件?

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

可以在早期的Python版本上使用。后一版本不是可重复使用..如果想要的话,可以做一个。

它不会在文件描述符级别重定向stdout,例如: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')

以前在stdout上打印的输出现在转到output.txt只要stdout_redirected()上下文管理器处于活动状态。

注:stdout.flush()不刷新Python 3上的C Stdio缓冲区,其中I/O是直接在Python 3上实现的read()/write()系统呼叫。要刷新所有打开的C Stdio输出流,可以调用libc.fflush(None)如果某些C扩展使用基于Stdio的I/O,则显式地: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()混合缓冲I/O(sys.stdout(通常)和未缓冲的I/O(直接对文件描述符的操作)。小心,可能会有缓冲 问题.

要回答,您的编辑:您可以使用python-daemon若要守护脚本并使用logging模块(AS)@erikb 85建议)而不是print语句,并仅重定向长期运行的Python脚本的stdout。nohup现在。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值