在IPython中嵌入交互式终端
在切换到 IPython v0.11(使用 Python 2.6.1)之前,可以通过一些方法嵌入一个互动的 IPython 终端,比如说这个。
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
“嵌入的终端已经被重构成一个真正独立的子类,叫做 InteractiveShellEmbed。所有的嵌入逻辑都被移出了基础类,放到了这个嵌入的子类里。”(详细信息可以查看这里和这里)。
根据我的理解,你现在应该可以简单地通过以下方式启动一个控制台:
import IPython
IPython.embed()
然而,这会引发一个错误:
TraitError: InteractiveShellEmbed 实例的 'exit_msg' 属性必须是一个字符串,但指定的值是 u''。
如果我们为 exit_msg
传递一个字符串:
IPython.embed(exit_msg='Whatever')
那么会出现另一个错误:
AttributeError: 'InteractiveShellEmbed' 对象没有 'set_completer' 这个属性。
有没有其他人遇到过这个问题?如果没有的话,这可能是一个bug,毕竟这是开发者版本。
2 个回答
3
在GitHub的维基页面上,有一些具体的说明。
from IPython.frontend.terminal.ipapp import TerminalIPythonApp
app = TerminalIPythonApp.instance()
app.initialize(argv=[]) # argv=[] instructs IPython to ignore sys.argv
app.start()
10
现在(3.0及以上版本),你只需要这样做:
from IPython import embed; embed()
如果你是想在IPython里面再嵌套一个IPython窗口(也就是递归地嵌套),之前有很长一段时间是不支持的,但这个问题去年已经修复了。