【发布时间】:2015-04-02 20:31:50
【问题描述】:
我正在尝试将 iPython Qtconsole 嵌入到 PyQt5 应用程序中。嵌入式控制台工作正常,但是当我尝试退出应用程序(通过单击“退出”,使用 Cmd-Q)时,Python 进程挂起,我必须强制退出以消除旋转的死亡沙滩球。这是在 OS X 10.10.2、Python 2.7.9、iPython 3.0.0 和 PyQt5 5.3.1 上。关于如何正确戒烟的任何想法?
最小的例子,改编自iPython examples:
#!/usr/bin/env python
from PyQt5 import Qt
from internal_ipkernel import InternalIPKernel
class SimpleWindow(Qt.QWidget, InternalIPKernel):
def __init__(self, app):
Qt.QWidget.__init__(self)
self.app = app
self.add_widgets()
self.init_ipkernel('qt')
def add_widgets(self):
self.setGeometry(300, 300, 400, 70)
self.setWindowTitle('IPython in your app')
# Add simple buttons:
self.console = Qt.QPushButton('Qt Console', self)
self.console.setGeometry(10, 10, 100, 35)
self.console.clicked.connect(self.new_qt_console)
self.namespace = Qt.QPushButton('Namespace', self)
self.namespace.setGeometry(120, 10, 100, 35)
self.namespace.clicked.connect(self.print_namespace)
self.count_button = Qt.QPushButton('Count++', self)
self.count_button.setGeometry(230, 10, 80, 35)
self.count_button.clicked.connect(self.count)
# Quit and cleanup
self.quit_button = Qt.QPushButton('Quit', self)
self.quit_button.setGeometry(320, 10, 60, 35)
self.quit_button.clicked.connect(self.app.quit)
self.app.lastWindowClosed.connect(self.app.quit)
self.app.aboutToQuit.connect(self.cleanup_consoles)
if __name__ == "__main__":
app = Qt.QApplication([])
# Create our window
win = SimpleWindow(app)
win.show()
# Very important, IPython-specific step: this gets GUI event loop
# integration going, and it replaces calling app.exec_()
win.ipkernel.start()
import sys
from IPython.lib.kernel import connect_qtconsole
from IPython.kernel.zmq.kernelapp import IPKernelApp
def mpl_kernel(gui):
"""Launch and return an IPython kernel with matplotlib support for the desired gui
"""
kernel = IPKernelApp.instance()
kernel.initialize(['python', '--matplotlib=%s' % gui,
#'--log-level=10'
])
return kernel
class InternalIPKernel(object):
def init_ipkernel(self, backend):
# Start IPython kernel with GUI event loop and mpl support
self.ipkernel = mpl_kernel(backend)
# To create and track active qt consoles
self.consoles = []
# This application will also act on the shell user namespace
self.namespace = self.ipkernel.shell.user_ns
# Example: a variable that will be seen by the user in the shell, and
# that the GUI modifies (the 'Counter++' button increments it):
self.namespace['app_counter'] = 0
#self.namespace['ipkernel'] = self.ipkernel # dbg
def print_namespace(self, evt=None):
print("\n***Variables in User namespace***")
for k, v in self.namespace.items():
if not k.startswith('_'):
print('%s -> %r' % (k, v))
sys.stdout.flush()
def new_qt_console(self, evt=None):
"""start a new qtconsole connected to our kernel"""
return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
def count(self, evt=None):
self.namespace['app_counter'] += 1
def cleanup_consoles(self, evt=None):
for c in self.consoles:
c.kill()
【问题讨论】: