33

我想将以下 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)

我只想将“欢迎来到我的谈话”部分捕获到我的文件中。

4

4 回答 4

44

使用 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
于 2015-09-23T05:10:38.587 回答
29

只需执行以下操作:

%save file_name.py _oh[7]

PS:一些额外的有用命令:

%save file_name.py _

'_' 指的是先前的输出。

或者您可以:

%save file_name.py _oh[i]

'i' 指的是输出历史编号,您可以通过以下方式首先查看输出:

_oh
于 2013-01-16T05:07:24.377 回答
5

如果您需要,单元格魔法会保存运行命令的 stdout/stderr输出%%capture这是使用语法:

%%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,它有一个简洁的接口用于访问 stdout/stderr 或组合输出。

于 2018-03-26T12:31:27.093 回答
1

IPython 捕获变量 _(下划线)中最后一个命令的值(输出)。

%edit some_variable

将在您的编辑器中打开一个变量的值。

因此,“%edit _”应该使您能够编辑和保存最后一个命令的值。

请参阅IPython 文档的历史记录部分

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

%edit?
于 2012-11-07T23:30:49.833 回答