python - 如何将 ipython 魔术输出存储到变量中

标签 python ipython ipython-magic

我是 python 和 Ipython 初学者。这可能是一个微不足道的问题。它可能与其他问题重复。但是我不知道应该搜索什么关键词。

我已经知道如何与 shell 交互。

例如:

In [1]: a = !ls
In [2]: a
        ...same ls result as shell...
In [3]: type(a)
Out[3]: IPython.utils.text.SList

但是,如何与Ipython magic交互呢?

例如

In [1]: a = %history -t 
        ...Ipython result...
In [2]: a
In [3]: type(a)
Out[3]: NoneType

最佳答案

对于history命令,具体来说,最简单的方案是

In [243]: history -t -f history.txt
In [244]: with open('history.txt') as f:
   .....:     HIST = [l.strip() for l in f]
   .....:     

In [245]: len(HIST)
Out[245]: 258

In [246]: HIST[-1]
Out[246]: "get_ipython().magic(u'history -t -f history.txt')"

In [247]: 

基本上,将其转储到文件中并读回。

这可能看起来有点乱七八糟,但我怀疑它来自 IPython 的本质。它实际上不是解释器,而是底层解释器的命令行 shell。我怀疑魔术命令是在 IPython 内部处理的,不会通过将命令传递给解释器、捕获输出并将其作为 Out[n] 存储在命令历史记录中的正常路径。因此它不可用于召回和分配。

另一种方法是 get_ipython().magic 简单地返回 None

无论哪种方式,屏幕输出 d=for %history 都不可用。您必须将其转储到文件中。

它似乎因魔法命令而异。 alias,例如,返回屏幕输出

In [288]: a=%alias
Total number of aliases: 17

In [289]: a
Out[289]: 
[('cat', 'cat'),
 ('clear', 'clear'),
 ('cp', 'cp'),
 ('ldir', 'ls -F -G -l %l | grep /$'),
 ('less', 'less'),
 ('lf', 'ls -F -l -G %l | grep ^-'),
 ('lk', 'ls -F -l -G %l | grep ^l'),
 ('ll', 'ls -F -l -G'),
 ('ls', 'ls -F -G'),
 ('lx', 'ls -F -l -G %l | grep ^-..x'),
 ('man', 'man'),
 ('mkdir', 'mkdir'),
 ('more', 'more'),
 ('mv', 'mv'),
 ('rm', 'rm'),
 ('rmdir', 'rmdir'),
 (u'show', u'echo')]

In [290]: 

关于python - 如何将 ipython 魔术输出存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059132/

相关文章:

python - Ipywidgets 在交互式而不是小部件上观察方法

python - Jupyter Lab/Notebook 魔法命令 %load 具有与平台无关的路径

python - 按预定义索引拆分 python 字符串

python - Nbconvertapp 不存在

python - pylint:忽略 rcfile 中的多个

IPython 在选项卡完成时崩溃

python - 以分离模式在 IPython Notebook 中运行一些任务

windows - 使用 Windows 7 从 IPython 复制到剪贴板

python - 所有迭代器都会缓存吗? csv.Reader 怎么样?

python - 安装 Python 2.6.2 的 Ubuntu 9.04 上的 mod_wsgi 2.5