IPython:将 Python 脚本的输出重定向到文件(如 bash >) [英] IPython: redirecting output of a Python script to a file (like bash >)

查看:21
本文介绍了IPython:将 Python 脚本的输出重定向到文件(如 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 有自己的 捕获标准输出/错误,但它不会重定向到文件,而是重定向到一个对象:

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

并且此功能在 %%capture 单元魔术中公开,如 Cell Magics 示例笔记本.

And this functionality is exposed in a %%capture cell-magic, as illustrated in the Cell Magics example notebook.

这是一个简单的上下文管理器,因此您可以编写自己的版本来重定向到文件:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆