如何将IPython命令的输出写入Python文本文件?

37

我想将以下ipython命令的输出捕获到文件中: 命令和输出如下:

`decoder.get_hyp()`

WARNING: "ngram_search.c", line 1000: </s> not found in last frame, using ++NOISE++ instead
INFO: ngram_search.c(1046): lattice start node <s>.0 end node ++NOISE++.171
INFO: ps_lattice.c(1225): Normalizer P(O) = alpha(++NOISE++:171:185) = -2003082
INFO: ps_lattice.c(1263): Joint P(O,S) = -2036704 P(S|O) = -33622
Out[7]: ('WELCOME TO MY TALK', '000000000', -36704586)

我想把"wellcome to my talk"这部分内容单独提取出来放到我的文件里。

4个回答

49

使用IPython的魔术函数store

%store foo >a.txt # Store (overwrite) value of foo to file a.txt

%store foo >>a.txt # Append value of foo to file a.txt

1
有没有一种类似的方法可以将其读回到变量中?比如,我将一个列表存储到了一个 .txt 文件中,现在我想要将这个 .txt 文件读取回一个变量中。谢谢。 - Moondra
你可以使用 %load 进行尝试,但最佳实践是使用pickle存储文件。 - SeF
请注意,使用 %store 命令保存的数据类型(如 str)会被保存为 (<class 'str'>,) 的形式,当使用 %load 命令加载时会引发错误... 因此建议使用 pickle! - SeF
请注意,要使其正常工作,您必须像这样输入:%store foo> a.txt。如果您以这种方式输入:%store foo> a.txt,您将收到FileNotFound错误。 - Pepe Alvarez

30

按照以下步骤执行:

%save file_name.py _oh[7]

附加提示:一些有用的额外命令:

%save file_name.py _
'

'_'指代先前的输出。

或者你可以:

'
%save file_name.py _oh[i]

'i'指的是输出历史记录的数字,您可以通过以下方式首先查看输出:

_oh

6
< p > %%capture单元格魔法命令可以保存运行命令时的stdout/stderr输出,如果您需要的话。以下是用法语法:

%%capture [--no-stderr] [--no-stdout] [--no-display] [output]

以下是一个使用示例:

In [1]: %%capture my_print_output
    ...: print('test')
    ...:

In [2]: my_print_output
Out[2]: <IPython.utils.capture.CapturedIO at 0x7f2efa2c12d0>

In [3]: test_output.show()
test

输出对象是 IPython.utils.capture.CapturedIO 的一个实例,它具有方便的接口,用于访问标准输出、标准错误或组合输出。

2
没错。你应该使用 x=my_print_output.stdout %store x > file - user2679290

1

IPython 会将上一个命令的值(输出)保存在变量 _(下划线)中。

%edit some_variable

将打开编辑器中变量的值。

因此,"%edit _" 应该可以让您编辑并保存最后一次命令的值。

请参见 IPython文档的历史部分

如果想了解 %edit 魔术函数的可能参数,请在 IPython 提示符下键入以下内容:

%edit?

嗯,当我在numpy数组上尝试这个时,我得到了“'NoneType' object is not iterable”的错误。 - Amelio Vazquez-Reina

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接