“get_ipython”在IPython / IPython Notebook的启动脚本中无法运行…?

3
所以,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个回答

5

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

from IPython import get_ipython
ipython_shell = get_ipython()

此外,当导入 .py 文件和 .ipy 文件时,ipython 的行为不同。你可以尝试将 rootprint 保存为 .ipy 文件。
如果这种方法可行,我不确定是否能被称为解决方案,但它可能会指引你朝着正确的方向前进。

0

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

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(RootMagics)

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