`get_ipython'在IPython / IPython Notebook的启动脚本中不起作用?

时间:2014-02-04 01:20:02

标签: ipython ipython-notebook ipython-magic

所以 - ROOT社区中的优秀人员产生了以下魔力:

# This is for intercepting the output of ROOT
# In a cell, put %%rootprint so that the output that would normally be
# sent directly to the stdout will instead be displayed in the cell.
# It must be the first element in the cell.
import tempfile
import ROOT
from IPython.core.magic import (Magics, magics_class, cell_magic)

@magics_class
class RootMagics(Magics):
    """Magics related to Root.

    %%rootprint  - Capture Root stdout output and show in result cell
    """

    def __init__(self, shell):
        super(RootMagics, self).__init__(shell)

    @cell_magic
    def rootprint(self, line, cell):
        """Capture Root stdout output and print in ipython notebook."""

        with tempfile.NamedTemporaryFile() as tmpFile:

            ROOT.gSystem.RedirectOutput(tmpFile.name, "w")
            # ns = {}
            # exec cell in self.shell.user_ns, ns
            exec cell in self.shell.user_ns
            ROOT.gROOT.ProcessLine("gSystem->RedirectOutput(0);")
            print tmpFile.read()

# Register
ip = get_ipython()
ip.register_magics(RootMagics)

如果我在我的IPython笔记本中的单元格中import rootprint,那么这很有效 - 没有投诉,而且一切都按预期工作。但是,现在我想导入这个并在〜/ .ipython / profile / startup中的python文件中做一些东西 - 该目录中的python文件显然在IPython启动时首先运行,允许访问你在其中定义的任何内容。如果我只是做一些简单的事情(不是import rootprint),一切都按预期工作 - 我可以在启动脚本中创建一个函数,稍后随意使用它。但是当我在启动脚本中尝试import rootprint然后启动IPython(只是IPython,而不是现在的笔记本)时,它就会出现抱怨:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/lib/python2.6/site-packages/ipython-1.1.0-py2.6.egg/IPython/utils/py3compat.pyc in execfile(fname, *where)
    202             else:
    203                 filename = fname
--> 204             __builtin__.execfile(filename, *where)

/home/wjmills/.ipython/profile_nbserver/startup/dummy.py in <module>()
      2 import ROOT
      3 from ROOT import gROOT, TCanvas, TF1, TFile, TTree, gRandom, TH1F
----> 4 import numpy, rootprint
      5 
      6 def foo():

/home/wjmills/.ipython/profile_nbserver/startup/rootprint.py in <module>()
     31 
     32 # Register
---> 33 ip = get_ipython()
     34 ip.register_magics(RootMagics)

NameError: name 'get_ipython' is not defined

在profile / startup启动时运行python脚本的上下文中get_ipython会发生什么?同样,如果我从IPython笔记本中交互式地完成这一切,这一切都很完美,所以它似乎是关于启动过程的特别之处。提前致谢!

2 个答案:

答案 0 :(得分:5)

这是一个不完整的建议 - 但如果get_ipython还没有在命名空间中,你可以尝试直接导入它:

from IPython import get_ipython
ipython_shell = get_ipython()

此外,ipython在导入.py文件与.ipy文件时有不同的行为。您可以尝试将rootprint保存为.ipy文件。

我不确定如果它有效,我会将其归类为解决方案,但它可能会指向正确的方向。

答案 1 :(得分:0)

我认为注册魔法的首选方式是

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(RootMagics)
相关问题