IPython:将Python脚本的输出重定向到文件(比如bash>)

2024-04-29 06:00:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本要在IPython中运行。我想将输出重定向(写入)到一个文件,类似于:

python my_script.py > my_output.txt

如何在IPython中运行脚本,例如execfile('my_script.py')

有一个older page描述了一个函数,它可以被编写来完成这个任务,但是我相信现在有一个内置的方法来完成这个任务,我只是找不到。


Tags: 文件方法函数pytxt脚本outputmy
3条回答

虽然这是一个老问题,但当我面对一个类似的问题时,我找到了这个问题和答案。

我在筛选IPython Cell magics documentation之后找到的解决方案实际上相当简单。最基本的解决方案是将命令的输出分配给变量。

这个简单的双单元示例演示了如何做到这一点。在第一个笔记本单元中,我们使用%%writefile单元魔术定义了Python脚本,并将其输出到stdout

%%writefile output.py
print("This is the output that is supposed to go to a file")

然后,我们运行该脚本,就像它是使用!运算符从shell运行一样。

output = !python output.py
print(output)
>>> ['This is the output that is supposed to go to a file']

然后您可以很容易地使用%store魔术来持久化输出。

%store output > output.log

但是请注意,命令的输出将作为行列表持久化。在存储输出之前,您可能需要调用"\n".join(output)

IPython有自己的capturing stdout/err上下文管理器,但它不重定向到文件,而是重定向到一个对象:

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 example notebook所示。

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

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中工作时,简单地查看变量中包含的大量文本。这就是我的工作:

%store VARIABLE >> file.txt(附录)
%store VARIABLE > file.txt(覆盖)

相关问题 更多 >