如何在没有终端提示的情况下从IPython会话中复制 [英] How to Copy from IPython session without terminal prompts

查看:118
本文介绍了如何在没有终端提示的情况下从IPython会话中复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作流程经常涉及IPython shell中的数据清理/修改。自从IPython 5.0版本以及所有优秀的以来,这一点变得特别精彩。升级到终端界面。所以,假设我试图修改一些非结构化数据:

Frequently, my workflow involves data cleaning/munging in an IPython shell. This has become particularly wonderful since IPython version 5.0 with all the great upgrades to the terminal interface. So, let's say I make an attempt at sprucing up some piece of unstructured data:

In [11]: for i, (num, header, txt) in enumerate(data):
    ...:     header = [e.strip() for e in header.strip().split('\n')]
    ...:     header[4] = header[4].strip(',').split(',')
    ...:     data[i] = (num, header, txt)
    ...:

很棒,很有效!但现在,我真的想将它添加到我的编辑器中的脚本中。如果我从终端复制并粘贴,我会捕获左边的所有垃圾。我可以在编辑器中轻松地清理它,但是如果我可以直接将代码从终端直接复制到我的剪贴板而不触摸鼠标并且没有抓住额外的东西,这将是很好的。在IPython中有这样的功能吗?

Fantastic, it works! But now, I would really like to add this to a script in my editor. If I copy and paste from my terminal, I capture all the junk on the left. I can clean this up more-or-less easily in an editor, but it would be great if I could copy the code directly to my clipboard from the terminal without touching the mouse and without grabbing the extra stuff either. Is there such a functionality in IPython?

推荐答案

你可以使用%history 魔术从你的会话中提取有趣的部分。它们将在没有任何垃圾的终端中显示。

You can use the %history magic to extract the interesting parts from your session. They will be shown in terminal without any of the junk.

In [1]: import numpy as np    
In [2]: a = np.random(10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-83ce219ad17b> in <module>()
----> 1 a = np.random(10)

TypeError: 'module' object is not callable

In [3]: a = np.random.random(10)
In [4]: for i in a:
   ...:     print(i)
   ...:     
0.688626523886
[...]
0.341394850998

如果我想保存会话的一部分,我可以使用:

If I want to save a part of the session above I can use:

In [5]: %history 1 3-4

import numpy as np
a = np.random.random(10)
for i in a:
    print(i)

在上面的示例中,我使用%history 1 3-4 来汇编我想要保留的所有命令,并省略我不需要的命令(第2行,第1行)有错误)。现在你的会话版本可以很好地复制。

In the example above I used %history 1 3-4 to assemble all the commands I want to keep and omit the ones I do not need (Line 2, the one with the error). Now you have version of your session that can be nicely copied.

你也可以直接使用 -f FILENAME 作为参数将此文件写入文件。

You can also directly write this to file using the -f FILENAME as parameter.

In [8]: %history 1 3-4 -f /tmp/foo.py

虽然要小心,这将覆盖现有文件
更多细节可以在 <的文档中找到code>%历史记录魔力

Be careful though, this will overwrite existing files. More Details can be found in the documentation of the %history magic.

这篇关于如何在没有终端提示的情况下从IPython会话中复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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