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现在。
python stdout_将stdout重定向到Python中的文件?相关推荐
- 将stdout重定向到Python中的文件?
本文翻译自:Redirect stdout to a file in Python? How do I redirect stdout to an arbitrary file in Python? ...
- python上传大文件s3_使用Python boto3上传Windows EC2实例中的文件至S3存储桶中
一.创建终端节点 为什么要创建终端节点,把VPC和S3管理起来呢?如果不将VPC和S3通过终端节点管理起来,那么VPC中EC2实例访问S3存储桶是通过公共网络的:一旦关联起来,那么VPC中EC2实例访 ...
- python django下载 功能如何实现_Python中django文件传输下载功能的实现
Python中django文件传输下载功能的实现,基于Django建立的网站,如果提供文件下载功能,最简单的方式莫过于将静态文件交给Nginx等处理,但有些时候,由于网站本身逻辑,需要通过Django ...
- python zipfile模块,关于python:使用ZipFile模块从zipfile中删除文件
我想从zip文件中删除文件的唯一方法是创建一个临时zipfile,而不删除该文件,然后将其重命名为原始文件名. 在python 2.4中,ZipInfo类具有属性file_offset,因此可以创建第 ...
- linux将什么定向到文件,linux – 将输出重定向到C中的文件
这是我用dup2测试的结果 更微妙的一点是在正确的时间记住fflush :)否则,你会得到非常令人惊讶的结果. 此外,更喜欢fileno而不是硬编码1(stdout)2(stderr). 重定向std ...
- python输出可执行文件_重定向-禁止在Python调用中输出可执行文件
重定向-禁止在Python调用中输出可执行文件 我有一个名为B的二进制文件,该文件在调用时会生成输出. 如果从Bash shell调用它,则大多数输出将受到A > /dev/null的抑制.所有 ...
- Python的sys.stdout、sys.stdin重定向
Python的sys.stdout.sys.stdin重定向 转自:http://www.cnblogs.com/turtle-fly/p/3280519.html 本文环境:Python 2.7 使 ...
- python读取print输出的内容_Python文件中将print的输出内容重定向到变量中
有时候需要用到别人的代码, 但是又不想修改别人的文件, 想拿到输出的结果, 这时候就需要使用sys模块, 将print输出的内容重定向到变量中. Python调用sys模块中的sys.stdout, ...
- python stdout_python--几种标准输出(stdout)重定向方式
系统:windows为主 python 版本:2.7 1. 背景 在Python中,文件对象sys.stdin.sys.stdout和sys.stderr分别对应解释器的标准输入.标准输出和标准出错流 ...
最新文章
- FPGA的配置引脚以及配置过程
- python获取文本光标_python 文件的操作以及调整光标
- 2021-06-29
- 【技术综述】有三AI不得不看的技术综述
- 开源虎墩同名电影《小虎墩大英雄》定档大年初一
- 前端学习(1049):todolist正在进行和已经完成阶段2
- VC创建DLL动态链接库及其调用
- 作者:袁明轩(1980-),男,华为诺亚方舟实验室研究员。
- pytorch torch.randn
- 已有打开的与此命令相关联的 DataReader,必须首先将它关闭
- 客户机操作系统已禁用 cpu_强实时工业互联网虚拟化操作系统Intewell
- 解决Macbook安装win10/win11时遇到的WDF_Violation 蓝屏错误问题 - 安装Bootcamp驱动蓝屏
- armbian 斐讯n1_斐讯N1刷Armbian Linux做服务器
- windows windows计划任务访问网络存储NAS的问题
- CentOS 7 搭建DHCP中继服务
- 网络工程师——Super VLAN
- JavaScript实现垃圾分类小游戏教程,附源码!
- 加密货币、区块链不断贴近生活,阿里、腾讯、脸书等大厂们在做什么?
- 一键卸载电脑自带Office2003
- 版本管理之SVN实践教程:基础篇(5):提交/解决冲突/回退/确认