所以 - 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 笔记本以交互方式执行此操作,这一切都可以完美运行,因此启动过程似乎有些特别。提前致谢!