所以,ROOT社区的好心人进行了以下魔法:
在从配置文件/profile/startup中运行的Python脚本上下文中,
# 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笔记本进行交互操作,这一切都可以完美地工作,因此似乎有关启动过程的某些特殊事项。谢谢!