我将Python嵌入到PyQt4应用程序中,那时它还处于beta阶段,并且只在Ipython的一个git分支上工作。我已经一年多没有看过代码了,从那以后,代码发生了很大的变化--在Ipython中似乎有很多重构。我现在已经安装了13.2
因此,我需要嵌入Python,并且我需要它存在于我的PyQt4应用程序中,这样我就可以用我的Python中的数据来修改内核的user_ns。用于对抗git的python版本的代码如下所示:
import sys
sys.path.insert(0, "../../ipython") #pickup ipython from git in a nonstd dir
from IPython.embedded.ipkernel import EmbeddedKernel
from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.frontend.qt.embedded_kernelmanager import QtEmbeddedKernelManager
from IPython.lib import guisupport
from PyQt4.QtGui import QFrame,QHBoxLayout
from PyQt4.QtGui import QApplication
from collections import namedtuple
class IpythonEmbeddedWidget(QFrame):
def __init__(self):
QFrame.__init__(self)
self._layout = QHBoxLayout()
self._kernel = EmbeddedKernel()
self._kernel_manager = QtEmbeddedKernelManager(kernel = self._kernel)
self._kernel_manager.start_channels()
self._kernel.frontends.append(self._kernel_manager)
self._shell_widget = RichIPythonWidget()
app = guisupport.get_app_qt4()
self._shell_widget.exit_requested.connect(app.quit)
self._shell_widget.kernel_manager = self._kernel_manager
self._layout.addWidget(self._shell_widget)
self.setLayout(self._layout)
self._kernel.shell.run_cell("import nltk")
self._kernel.shell.run_cell("import sys")
self._kernel.shell.run_cell("sys.path.append('../ipython_scripts')")
self._kernel.shell.run_cell("cd ../ipython_scripts")
def set_shell_focus(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
iew = IpythonEmbeddedWidget()
iew.show()
app.exec_()
sys.exit()那么,要让它与当前的Ipython (13.2)版本一起工作,我需要更改什么呢?
编辑:
13.2没有进程内内核的功能。你还需要开发部门。促使我问这个问题的不是我更新了我的开发分支,而是在我的机器上更新了QT/PyQt4 4,使现有的代码中断了。随后,我更新了Ipython开发版本,它要求我在API更改后重构我的代码。
发布于 2013-05-24 15:13:08
我走了同样的路,但最后使用了IPython开发,因为嵌入解决方案更干净,没有令人讨厌的input() / help()错误。
这里有一个解决方案-- 0.13.x:https://stackoverflow.com/a/12375397/532513 --问题是,如果您使用help(),所有东西都会结冰。
在开发IPython中,这一切都要简单得多。下面是一个有用的例子:
from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.frontend.qt.inprocess import QtInProcessKernelManager
from IPython.lib import guisupport
from PyQt4.QtGui import QApplication
app = QApplication(sys.argv)
kernel_manager = QtInProcessKernelManager()
kernel_manager.start_kernel()
kernel = kernel_manager.kernel
kernel.gui = 'qt4'
kernel_client = kernel_manager.client()
kernel_client.start_channels()
def stop():
kernel_client.stop_channels()
kernel_manager.shutdown_kernel()
# here you should exit your application with a suitable call
sys.exit()
widget = RichIPythonWidget()
widget.kernel_manager = kernel_manager
widget.kernel_client = kernel_client
widget.exit_requested.connect(stop)
widget.setWindowTitle("IPython shell")
ipython_widget = widget
ipython_widget.show()
app.exec_()
sys.exit()发布于 2013-05-26 01:20:15
下面是我做的一些东西,我在PyQt4和PySide应用程序QIPythonWidget中都使用过。我没有在IPython上做任何工作,我只是对它进行了黑客攻击,所以可能有更好的方法来实现它,但这是可行的,并且没有遇到问题。希望能帮上忙。
https://stackoverflow.com/questions/16737323
复制相似问题