IPython:将Python脚本的输出重定向到文件(如bash>) [英] IPython: redirecting output of a Python script to a file (like bash >)
问题描述
我有一个我想在IPython中运行的Python脚本。我想将输出重定向(写入)到文件,类似于:
I have a Python script that I want to run in IPython. I want to redirect (write) the output to a file, similar to:
python my_script.py > my_output.txt
我在IPython中运行脚本时如何执行此操作,例如 execfile('my_script.py')
How do I do this when I run the script in IPython, i.e. like execfile('my_script.py')
有一个旧页面描述了可以编写的功能,但我相信现在有一个内置的这样做的方式,我找不到。
There is an older page describing a function that could be written to do this, but I believe that there is now a built-in way to do this that I just can't find.
推荐答案
IPython有自己的捕获stdout / err ,但它没有重定向到文件,它重定向到一个对象:
IPython has its own context manager for capturing stdout/err, but it doesn't redirect to files, it redirects to an object:
from IPython.utils import io
with io.capture_output() as captured:
%run my_script.py
print captured.stdout # prints stdout from your script
这个功能是在<$ h $ => http://nbviewer.ipython.org/urls/raw.github.com/中说明ipython / ipython / master / examples / notebooks / Cell%20Magics.ipynbrel =noreferrer> Cell Magics示例笔记本。
这是一个简单的上下文经理,所以你可以编写自己的版本,重定向到文件:
It's a simple context manager, so you can write your own version that would redirect to files:
class redirect_output(object):
"""context manager for reditrecting stdout/err to files"""
def __init__(self, stdout='', stderr=''):
self.stdout = stdout
self.stderr = stderr
def __enter__(self):
self.sys_stdout = sys.stdout
self.sys_stderr = sys.stderr
if self.stdout:
sys.stdout = open(self.stdout, 'w')
if self.stderr:
if self.stderr == self.stdout:
sys.stderr = sys.stdout
else:
sys.stderr = open(self.stderr, 'w')
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout = self.sys_stdout
sys.stderr = self.sys_stderr
您可以调用:
with redirect_output("my_output.txt"):
%run my_script.py
这篇关于IPython:将Python脚本的输出重定向到文件(如bash>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!