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)

如果我import rootprint在我的 IPython 笔记本的一个单元格中做 ye olde,这将非常有用 - 没有抱怨,一切都按预期工作。但是,现在我想导入它并在 ~/.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

get_ipython在从配置文件/启动启动时运行的 python 脚本的上下文中会发生什么?同样,如果我从 IPython 笔记本以交互方式执行此操作,这一切都可以完美运行,因此启动过程似乎有些特别。提前致谢!

4

2 回答 2

6

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

from IPython import get_ipython
ipython_shell = get_ipython()

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

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

于 2014-07-30T22:34:43.037 回答
0

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

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(RootMagics)
于 2014-04-02T17:22:20.160 回答