gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:27:44 25 4
gpt4 key购买 nike

所以 - 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 文件中做一些事情 - 当 IPython 启动时,该目录中的 python 文件显然首先运行,允许访问您在其中定义的任何内容。如果我只是做一些简单的事情(不 import rootprint),一切都会按预期工作 - 我可以在启动脚本中创建一个函数并在以后随意使用它。但是,当我尝试在启动脚本中 import rootprint 然后启动 IPython(只是 IPython,暂时不是 notebook)时,它会提示:

---------------------------------------------------------------------------
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

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

最佳答案

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

from IPython import get_ipython
ipython_shell = get_ipython()

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

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

关于ipython - `get_ipython' 在 IPython/IPython Notebook 的启动脚本中不起作用...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com