def __init__(self, gui,*args, **kwargs): import ngsolve super().__init__(*args,**kwargs) self.gui = gui self.banner = """NGSolve %s Developed by Joachim Schoeberl at 2010-xxxx Vienna University of Technology 2006-2010 RWTH Aachen University 1996-2006 Johannes Kepler University Linz """ % ngsolve.__version__ multikernel_manager = gui.multikernel_manager if multikernel_manager is not None: self.kernel_id = multikernel_manager.start_kernel() self.kernel_manager = multikernel_manager.get_kernel(self.kernel_id) else: self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel_manager.kernel.gui = 'qt' self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() class dummyioloop(): def call_later(self,a,b): return def stop(self): return self.kernel_manager.kernel.io_loop = dummyioloop() def stop(): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() self.exit_requested.connect(stop)
def put_ipy(parent): kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() kernel_client.namespace = parent #kernel.execute_request("a=1",0, {'silent': False}) def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() layout = _gui.QVBoxLayout(parent) widget = RichIPythonWidget(parent=parent) layout.addWidget(widget) widget.kernel_manager = kernel_manager widget.kernel_client = kernel_client widget.exit_requested.connect(stop) ipython_widget = widget ipython_widget.show() kernel.shell.push({'widget':widget,'kernel':kernel, 'parent':parent}) return {'widget':widget,'kernel':kernel}
def put_ipy(parent): kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() kernel_client.namespace = parent def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() layout = QtWidgets.QVBoxLayout(parent) widget = RichJupyterWidget(parent=parent) layout.addWidget(widget) widget.kernel_manager = kernel_manager widget.kernel_client = kernel_client widget.exit_requested.connect(stop) ipython_widget = widget ipython_widget.show() kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent}) return {'widget': widget, 'kernel': kernel}
def __init__(self, *args): super(MainWindow, self).__init__(*args) self.setupUi(self) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.jupiter_widget.kernel_manager = self.kernel_manager self.jupiter_widget.kernel_client = self.kernel_client self.jupiter_widget.reset() self.reg_view.setColumnCount(2) self.reg_view.setHorizontalHeaderLabels(['Name', 'Value']) self.var_view.setColumnCount(4) self.var_view.setHorizontalHeaderLabels( ['Name', 'Type', 'Address', 'Value']) # NOTE: icons are from Google Material Design self.up_button.setIcon( QIcon(str(APP_ROOT.join('frontend/icon/up.png')))) self.up_button.setIconSize(QSize(15, 15)) self.up_button.clicked.connect(self.push_up) self.up_button.setEnabled(False) self.upto_button.setIcon( QIcon(str(APP_ROOT.join('frontend/icon/upto.png')))) self.upto_button.setIconSize(QSize(15, 15)) self.upto_button.clicked.connect(self.push_upto) self.upto_button.setEnabled(False) self.down_button.setIcon( QIcon(str(APP_ROOT.join('frontend/icon/down.png')))) self.down_button.setIconSize(QSize(15, 15)) self.down_button.clicked.connect(self.push_down) self.down_button.setEnabled(False) self.downto_button.setIcon( QIcon(str(APP_ROOT.join('frontend/icon/downto.png')))) self.downto_button.setIconSize(QSize(15, 15)) self.downto_button.clicked.connect(self.push_downto) self.downto_button.setEnabled(False) self.cg_button.clicked.connect(self.push_callgraph) self.cg_button.setEnabled(False) self.info_button.clicked.connect(self.push_info) self.info_button.setEnabled(False) self.switch_button.clicked.connect(self.push_switch) self.switch_button.setEnabled(False) self.time_slider.setEnabled(False) self.file_cache = {} self.file_read_cache = {} self.callgraph = CallGraphManager() self.coredump_constraints = []
def __init__(self, main_window): """ desc: Constructor. arguments: main_window: The main window object. """ super(ipython_console, self).__init__(main_window) kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() self.kernel = kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.banner1 = '' kernel_client = kernel_manager.client() kernel_client.start_channels() self.control = RichIPythonWidget() self.control.banner = self.banner() self.control.kernel_manager = kernel_manager self.control.kernel_client = kernel_client self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(self.verticalLayout) self.verticalLayout.addWidget(self.control)
def add_repl(self,): """ Create a new Jupyter REPL session. """ self.repl = QtInProcessKernelManager() self.repl.start_kernel(show_banner=False) self.view.add_jupyter_repl(self.repl)
class JupyterWidget(QWidget): _defaultWidth = 900 _defaultHeight = 450 def __init__(self): super(JupyterWidget, self).__init__() self._kernel_manager = QtInProcessKernelManager() self._kernel_manager.start_kernel(show_banner=True) self._kernel_client = self._kernel_manager.client() self._kernel_client.start_channels() self._kernel = self._kernel_manager.kernel self._kernel.gui = 'qt4' self._console = RichJupyterWidget() self._console.kernel_manager = self._kernel_manager self._console.kernel_client = self._kernel_client self._layout = QHBoxLayout() self._layout.addWidget(self._console) self._layout.setContentsMargins(QMargins(0, 0, 0, 0)) self.setLayout(self._layout) self.resize(self._defaultWidth, self._defaultHeight) def push(self, name, value): self._kernel.shell.push({name: value})
def main(): # Print the ID of the main process print_process_id() init_asyncio_patch() app = guisupport.get_app_qt4() # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push({'foo': 43, 'print_process_id': print_process_id}) kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
class JupyterWidget(RichJupyterWidget): def __init__(self): super(RichJupyterWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt4().exit() self.exit_requested.connect(stop) def executeCmd(self, cmd): self.kernel.shell.ex(cmd) def evaluateCmd(self, cmd): self.kernel.shell.ev(cmd) def pushVar(self, **kwarg): self.kernel.shell.push(kwarg) def executeFile(self, file): """Execute a Python file in the interactive namespace.""" self.shell.safe_execfile(file, self.shell.user_global_ns) def runCell(self, *args, **kwargs): """Execute a cell.""" self.shell.run_cell(*args, **kwargs)
def __init__(self, session, tool_name): ToolInstance.__init__(self, session, tool_name) # 'display_name' defaults to class name with spaces inserted # between lower-then-upper-case characters (therefore "Tool UI" # in this case), so only override if different name desired self.display_name = "ChimeraX Python Shell" from chimerax.ui import MainToolWindow self.tool_window = MainToolWindow(self) parent = self.tool_window.ui_area # UI content code from ipykernel.ipkernel import IPythonKernel save_ns = IPythonKernel.user_ns IPythonKernel.user_ns = {'session': session} from qtconsole.inprocess import QtInProcessKernelManager kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels() from qtconsole.rich_jupyter_widget import RichJupyterWidget self.shell = RichJupyterWidget(parent) def_banner = self.shell.banner self.shell.banner = "{}\nCurrent ChimeraX session available as 'session'.\n\n".format( def_banner) self.shell.kernel_manager = kernel_manager self.shell.kernel_client = kernel_client IPythonKernel.user_ns = save_ns from PyQt5.QtWidgets import QHBoxLayout layout = QHBoxLayout() layout.addWidget(self.shell) layout.setStretchFactor(self.shell, 1) parent.setLayout(layout) self.tool_window.manage(placement=None)
def show(): """ An example of embedding a RichJupyterWidget with an in-process kernel. We recommend using a kernel in a separate process as the normal option - see embed_qtconsole.py for more information. In-process kernels are not well supported. To run this example: python3 inprocess_qtconsole.py """ #global ipython_widget # Prevent from being garbage collected # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=True) # kernel = kernel_manager.kernel # kernel.gui = 'qt5' kernel_client = kernel_manager.client() kernel_client.start_channels() ipython_widget = RichJupyterWidget() ipython_widget.kernel_manager = kernel_manager ipython_widget.kernel_client = kernel_client return ipython_widget
def startIPython(self): """ Create an IPython kernel manager and kernel. Add modules to its namespace. """ # make sure we only log errors and above from ipython logging.getLogger('ipykernel').setLevel(logging.WARNING) self.log.debug('IPy activation in thread {0}'.format( QtCore.QThread.currentThreadId())) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.namespace = self.kernel.shell.user_ns self.namespace.update({ 'np': np, 'config': self._manager.tree['defined'], 'manager': self._manager }) if _has_pyqtgraph: self.namespace['pg'] = pg self.updateIPythonModuleList() self.kernel.gui = 'qt4' self.log.info('IPython has kernel {0}'.format( self.kernel_manager.has_kernel)) self.log.info('IPython kernel alive {0}'.format( self.kernel_manager.is_alive())) self._manager.sigModulesChanged.connect(self.updateIPythonModuleList)
def start_kernel_manager(self, silo, ui): kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' def EulerAngles(name, roll, pitch, yaw, *args, **kwargs): from signal_logger.rotation_signals import EulerAnglesZyxSignal return EulerAnglesZyxSignal.from_constant(name, silo.times, roll, pitch, yaw, *args, **kwargs) def clf(): import pylab pylab.clf() ui.tab.ui.canvas.canvas.draw() def plot(signal, *args, **kwargs): # TODO(scaron): currently plots to the right axis, give choice signal.plot(*args, **kwargs) ui.tab.ui.canvas.canvas.draw() kernel_manager.kernel.shell.push({ 'EulerAngles': EulerAngles, 'clf': clf, 'plot': plot, 'pi': numpy.pi, 'silo': silo, 'ui': ui, }) self.kernel_manager = kernel_manager
def createConsole(parent): """ disclaimer: this code is not mine. I copied it to get an embedded console It will be modified at some point to attempt interactability source: https://stackoverflow.com/a/26676570 :param parent: :return: """ kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() kernel_client.namespace = parent def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() layout = QVBoxLayout(parent) widget = RichJupyterWidget(parent=parent) layout.addWidget(widget, Qt.AlignRight) widget.kernel_manager = kernel_manager widget.kernel_client = kernel_client widget.exit_requested.connect(stop) ipython_widget = widget ipython_widget.show() kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent}) return {'widget': widget, 'kernel': kernel}
class LpyShellWidget(RichJupyterWidget, GraphicalStreamRedirection): def __init__(self, parent=None): """ :param parent: specifies the parent widget. If no parent widget has been specified, it is possible to exit the interpreter by Ctrl-D. """ RichJupyterWidget.__init__(self, parent) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel(show_banner=False) self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.shell = self.kernel.shell self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.kernel.locals = self.kernel.shell.user_ns # Multiple Stream Redirection GraphicalStreamRedirection.__init__(self, self.kernel.stdout, self.kernel.stderr)
def __init__(self, parent=None): """ :param parent: specifies the parent widget. If no parent widget has been specified, it is possible to exit the interpreter by Ctrl-D. """ if sys.executable.endswith('pythonw.exe'): lpylog = open(tempfile.gettempdir() + '/lpylog.txt', 'w') sys.stdout = lpylog sys.stderr = lpylog RichJupyterWidget.__init__(self, parent) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel(show_banner=False) self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt' self.shell = self.kernel.shell self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.kernel.locals = self.kernel.shell.user_ns
def __init__(self, *args, **kwargs): """ Parameters ---------- help_explorer: psyplot_gui.help_explorer.HelpExplorer or None A widget that can be used to show the documentation of an object ``*args, **kwargs`` Any other keyword argument for the :class:`qtconsole.rich_jupyter_widget.RichJupyterWidget """ kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel = kernel_manager.kernel kernel.gui = 'qt4' if not with_qt5 else 'qt' kernel_client = kernel_manager.client() kernel_client.start_channels() self.help_explorer = kwargs.pop('help_explorer', None) super(ConsoleWidget, self).__init__(*args, **kwargs) self.intro_msg = dedents(""" psyplot version: %s gui version: %s The console provides you the full access to the current project and plots. To make your life easier, the following modules have been imported - %s Furthermore, each time you change the selection or the content in the plot objects viewer, the `sp` (the selection) and `mp` (all arrays) variables in the console are adjusted. To disable this behaviour, set:: >>> import psyplot_gui >>> psyplot_gui.rcParams['console.auto_set_mp'] = False >>> psyplot_gui.rcParams['console.auto_set_sp'] = False To inspect and object in the console and display it's documentation in the help explorer, type 'Ctrl + I' or a '?' after the object""") % ( psyplot.__version__, psyplot_gui.__version__, '\n - '.join('%s as %s' % t for t in modules2import)) self.kernel_manager = kernel_manager self.kernel_client = kernel_client self.kernel_manager.kernel.shell.run_code( '\n'.join('import %s as %s' % t for t in modules2import)) self.exit_requested.connect(QtCore.QCoreApplication.instance().quit) # we overwrite the short cut here because the 'Ctrl+S' shortcut is # reserved for mainwindows save action self.export_action.setShortcut(QKeySequence( 'Ctrl+Alt+S', QKeySequence.NativeText)) psy.Project.oncpchange.connect(self.update_mp) psy.Project.oncpchange.connect(self.update_sp)
def in_process_console(console_class=RichIPythonWidget, **kwargs): """Create a console widget, connected to an in-process Kernel This only works on IPython v 0.13 and above Parameters ---------- console_class : The class of the console widget to create kwargs : Extra variables to put into the namespace """ km = QtInProcessKernelManager() km.start_kernel() kernel = km.kernel kernel.gui = 'qt4' client = km.client() client.start_channels() control = console_class() control.kernel_manager = km control.kernel_client = client control.shell = kernel.shell control.shell.user_ns.update(**kwargs) return control
def main(): """Start kernel manager and client, create window, run app event loop, auto execute some code in user namespace. A minimalist example is shown in qt_ip_test.py. NOTE: Make sure that the Qt v2 API is being used by IPython by running `export QT_API=pyqt` at the command line before running neuropy, or by adding it to `.bashrc`""" app = guisupport.get_app_qt4() if INPROCESS: from qtconsole.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from qtconsole.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() nw = NeuropyWindow() ipw = nw.ipw config_ipw(ipw) ipw.kernel_manager = km ipw.kernel_client = kc ipw.exit_requested.connect(nw.stop) nw.show() # execute some code through the frontend (once the event loop is running). # The output appears in the IPythonWidget (ipw). do_later(ipw.execute, 'run -i %s' % 'startup.py', hidden=True) do_later(ipw.execute, 'run -i %s' % 'globals.py', hidden=True) #guisupport.start_event_loop_qt4(app) # doesn't seem to work in IPy 5.3.0 app.exec_()
def __init__(self, *args, **kw): super(MantidIPythonWidget, self).__init__(*args, **kw) # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' # Figure out the full path to the mantidplotrc.py file and then %run it mantidplotpath = path.split( path.dirname(__file__))[0] # It's the directory above this one # print '[....] mantid plot path: ', mantidplotpath mantidplotrc = path.join(mantidplotpath, 'mantidplotrc.py') shell = kernel.shell shell.run_line_magic('run', mantidplotrc) # print '[DB...BAUnderstand]: shell run: ', mantidplotrc # These 3 lines replace the run_code method of IPython's InteractiveShell class (of which the # shell variable is a derived instance) with our method defined above. The original method # is renamed so that we can call it from within the our_run_code method. f = shell.run_code shell.run_code = types.MethodType(our_run_code, shell) shell.ipython_run_code = f kernel_client = kernel_manager.client() kernel_client.start_channels() self.kernel_manager = kernel_manager self.kernel_client = kernel_client self._mainApplication = None return
def main(): """Start kernel manager and client, create window, run app event loop""" app = guisupport.get_app_qt4() if INPROCESS: from qtconsole.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from qtconsole.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() widget = RichJupyterWidget() widget.kernel_manager = km widget.kernel_client = kc if CLEANSHUTDOWN: # slow exit on CTRL+D def stop(): kc.stop_channels() km.shutdown_kernel() app.exit() widget.exit_requested.connect(stop) else: # fast exit on CTRL+D widget.exit_requested.connect(app.quit) widget.show() guisupport.start_event_loop_qt4(app)
def __init__(self, customBanner=None, *args, **kwargs): super(ConsoleWidget_embed, self).__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner #self.font_size = 4 self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel(show_banner=True) self.kernel_manager.kernel.gui = 'qt' self.kernel = self.kernel_manager.kernel self.kernel_client = self._kernel_manager.client() self.kernel_client.start_channels() def _abort_queues(kernel): pass self.kernel_manager.kernel._abort_queues = _abort_queues #self._execute("kernel = %s"%fit, False) def stop(): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() self.guisupport.get_app_qt().exit() self.exit_requested.connect(stop)
def __init__(self, *args, **kwargs): """ A constructor matching that of RichJupyterWidget :param args: Positional arguments passed directly to RichJupyterWidget :param kwargs: Keyword arguments. The following keywords are understood by this widget: - startup_code: A code snippet to run on startup. the rest are passed to RichJupyterWidget """ startup_code = kwargs.pop("startup_code", "") super(InProcessJupyterConsole, self).__init__(*args, **kwargs) # create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt' # use a separate thread for execution shell = kernel.shell shell.run_code = async_wrapper(shell.run_code, shell) # attach channels, start kernel and run any startup code kernel_client = kernel_manager.client() kernel_client.start_channels() if startup_code: shell.ex(startup_code) self.kernel_manager = kernel_manager self.kernel_client = kernel_client # Override python input to raise a QInputDialog. kernel.raw_input = QAppThreadCall(input_qinputdialog)
def __init__(self, main_window): """ desc: Constructor. arguments: main_window: The main window object. """ super(ipython_console, self).__init__(main_window) kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() self.kernel = kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.banner1 = '' kernel_client = kernel_manager.client() kernel_client.start_channels() self.control = RichIPythonWidget() self.control.banner = self.banner() self.control.kernel_manager = kernel_manager self.control.kernel_client = kernel_client self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setContentsMargins(0,0,0,0) self.setLayout(self.verticalLayout) self.verticalLayout.addWidget(self.control)
def __init__(self, *args, **kw): super(MantidIPythonWidget, self).__init__(*args, **kw) # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' # Figure out the full path to the mantidplotrc.py file and then %run it from os import path mantidplotpath = path.split(path.dirname(__file__))[0] # It's the directory above this one mantidplotrc = path.join(mantidplotpath, 'mantidplotrc.py') shell = kernel.shell shell.run_line_magic('run',mantidplotrc) # These 3 lines replace the run_code method of IPython's InteractiveShell class (of which the # shell variable is a derived instance) with our method defined above. The original method # is renamed so that we can call it from within the our_run_code method. f = shell.run_code shell.run_code = types.MethodType(our_run_code, shell) shell.ipython_run_code = f kernel_client = kernel_manager.client() kernel_client.start_channels() self.kernel_manager = kernel_manager self.kernel_client = kernel_client
def __init__(self, client): QtWidgets.QWidget.__init__(self) self.client = client self.devices = {} # build layout layout = QtWidgets.QVBoxLayout(self) # tab widget for each connected device self.device_tabs = QtWidgets.QTabWidget() self.device_tabs.currentChanged.connect(self.onCurrentDeviceChanged) layout.addWidget(self.device_tabs) # ipython console for scripting kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels() self._console = RichIPythonWidget(font_size=9) self._console.kernel_manager = kernel_manager self._console.kernel_client = kernel_client layout.addWidget(self._console) # set device added and remove callbacks and connect client.deviceAdded.connect(self.addDevice) client.deviceRemoved.connect(self.removeDevice) client.connect() # push client and device map to console namespace dct = {"client": client, "devices": self.devices, "console": self._console} kernel_manager.kernel.shell.push(dct) self.resize(800, 500) self.setWindowTitle("Fpga Test Application")
class JupyterWidget(RichJupyterWidget): def __init__(self): super().__init__() if 'asyncio' in sys.modules: self._init_asyncio_patch() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() # Fix issue with Jupyter 5.0+, see https://github.com/ipython/ipykernel/pull/376 if hasattr(self.kernel_manager.kernel, '_abort_queue'): # noinspection PyProtectedMember self.kernel_manager.kernel._abort_queues = self.kernel_manager.kernel._abort_queue self.exit_requested.connect(self.stop) qApp.aboutToQuit.connect(self.stop) def _init_asyncio_patch(self): """set default asyncio policy to be compatible with tornado Tornado 6 (at least) is not compatible with the default asyncio implementation on Windows Pick the older SelectorEventLoopPolicy on Windows if the known-incompatible default policy is in use. do this as early as possible to make it a low priority and overrideable ref: https://github.com/tornadoweb/tornado/issues/2608 FIXME: if/when tornado supports the defaults in asyncio, remove and bump tornado requirement for py38 """ if sys.platform.startswith("win") and sys.version_info >= ( 3, 8) and tornado.version_info < (6, 1): import asyncio try: from asyncio import ( WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy, ) except ImportError: pass # not affected else: if type(asyncio.get_event_loop_policy() ) is WindowsProactorEventLoopPolicy: # WindowsProactorEventLoopPolicy is not compatible with tornado 6 # fallback to the pre-3.8 default of Selector asyncio.set_event_loop_policy( WindowsSelectorEventLoopPolicy()) def stop(self): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() def push(self, **kwargs): self.kernel_manager.kernel.shell.push(kwargs)
def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels()
def start_in_process_kernel(): global kernel_manager, kernel_client kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels()
class IPythonPlugin(GUIPlugin): name = 'IPython' def __init__(self): # # Enforce global style within the console # with open('xicam/gui/style.stylesheet', 'r') as f: # style = f.read() # style = (qdarkstyle.load_stylesheet() + style) # Setup the kernel self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() kernel = self.kernel_manager.kernel kernel.gui = 'qt' # Push Xi-cam variables into the kernel kernel.shell.push({ plugin.name: plugin for plugin in pluginmanager.get_plugins_of_type("GUIPlugin") + pluginmanager.get_plugins_of_type("EZPlugin") }) # Observe plugin changes pluginmanager.attach(self.pluginsChanged) # Continue kernel setuppluginmanager.getPluginsOfCategory("GUIPlugin") self.kernel_client = self.kernel_manager.client() threads.invoke_in_main_thread(self.kernel_client.start_channels) # Setup console widget def stop(): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() control = RichJupyterWidget() control.kernel_manager = self.kernel_manager threads.invoke_in_main_thread(setattr, control, "kernel_client", self.kernel_client) control.exit_requested.connect(stop) # control.style_sheet = style control.syntax_style = u'monokai' control.set_default_style(colors='Linux') # Setup layout self.stages = {'Terminal': GUILayout(control)} # Save for later self.kernel = kernel super(IPythonPlugin, self).__init__() def pluginsChanged(self): self.kernel.shell.push({ plugin.name: plugin for plugin in pluginmanager.get_plugins_of_type("GUIPlugin") + pluginmanager.get_plugins_of_type("EZPlugin") })
class ConsoleWidget_embed(RichJupyterWidget, ConsoleWidget): global fit def __init__(self, customBanner=None, *args, **kwargs): super(ConsoleWidget_embed, self).__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner #self.font_size = 4 self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel(show_banner=True) self.kernel_manager.kernel.gui = 'qt' self.kernel = self.kernel_manager.kernel self.kernel_client = self._kernel_manager.client() self.kernel_client.start_channels() def _abort_queues(kernel): pass self.kernel_manager.kernel._abort_queues = _abort_queues #self._execute("kernel = %s"%fit, False) def stop(): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() self.guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): """ Given a dictionary containing name / value pairs, push those variables to the Jupyter console widget """ self.kernel_manager.kernel.shell.push(variableDict) def clear(self): """ Clears the terminal """ self._control.clear() # self.kernel_manager def print_text(self, text, before_prompt=True): """ Prints some plain text to the console """ self._append_plain_text(text, before_prompt=before_prompt) def execute_command(self, command): """ Execute a command in the frame of the console widget """ self._execute(command, False)
def __init__(self, parent=None): super(RichIPythonWidget, self).__init__(parent) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' # self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.kernel.shell.run_cell('%pylab qt')
class EmbedIPython(RichIPythonWidget): def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels()
def __init__(self, *args): super(MainWindow, self).__init__(*args) self.setupUi(self) self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.jupiter_widget.kernel_manager = self.kernel_manager self.jupiter_widget.kernel_client = self.kernel_client self.jupiter_widget.reset()
def init_jupyter_kernel(cls, widget): """Start a kernel, connect to it, and create a RichJupyterWidget to use it """ kernel_manager = QtInProcessKernelManager(kernel_name="python3") kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels() widget.kernel_manager = kernel_manager widget.kernel_client = kernel_client
class IPythonView(RichJupyterWidget): """A view with an IPython console living in the same Python process as the GUI.""" def __init__(self, *args, **kwargs): super(IPythonView, self).__init__(*args, **kwargs) def start_kernel(self): """Start the IPython kernel.""" logger.debug("Starting the kernel.") self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel(show_banner=False) self.kernel_manager.kernel.gui = 'qt' self.kernel = self.kernel_manager.kernel self.shell = self.kernel.shell self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.set_default_style('linux') self.exit_requested.connect(self.stop) def inject(self, **kwargs): """Inject variables into the IPython namespace.""" logger.debug("Injecting variables into the kernel: %s.", ', '.join(kwargs.keys())) self.kernel.shell.push(kwargs) def attach(self, gui, **kwargs): """Add the view to the GUI, start the kernel, and inject the specified variables.""" gui.add_view(self) self.start_kernel() self.inject(gui=gui, **kwargs) try: import numpy self.inject(np=numpy) except ImportError: # pragma: no cover pass try: import matplotlib.pyplot as plt self.inject(plt=plt) except ImportError: # pragma: no cover pass @connect def on_close_view(sender, view): if view == self: self.stop() def stop(self): """Stop the kernel.""" logger.debug("Stopping the kernel.") self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel()
class EmbedIPython(RichJupyterWidget): """ Some voodoo to get an ipython console in a Qt application. """ def __init__(self, **kwarg): super(RichJupyterWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels()
class Ipython(object): def __init__(self, scripts_path=''): self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel sys.stdout = self.kernel.stdout sys.stderr = self.kernel.stderr self.scripts_path = scripts_path self.kernel.gui = 'qt4' self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.control = RichJupyterWidget() self.control.kernel_manager = self.kernel_manager self.control.kernel_client = self.kernel_client self.control.exit_requested.connect(self.stop) self.control.setWindowTitle("IPython shell") self.execute('import numpy as np') self.execute('from matplotlib import pyplot as plt') self.execute('%matplotlib') self.execute('') def __del__(self): self.stop() self.close() def show(self): self.control.show() self.control.setWindowState(self.control.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.control.activateWindow() def stop(self): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() def close(self): self.control.close() def push(self, vardic): self.kernel.shell.push(vardic) def execute(self, cmd): self.control.execute(cmd) def run_script(self, scriptname): scriptpath = os.path.join(self.scripts_path, scriptname) return self.control.execute('run -i %s' % scriptpath)
class IPythonConsole: def __init__(self, layout, sim, gui): # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.write("Welcome to AO Sim!") config = sim.config #Pass some useful objects to the user usefulObjects = { "sim" : sim, "gui" : gui, "config" : config, "simConfig" : sim.config.sim, "telConfig" : sim.config.tel, "atmosConfig" : sim.config.atmos} for i in range(sim.config.sim.nGS): usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i] for i in range(sim.config.sim.nDM): usefulObjects["dm{}Config".format(i)] = sim.config.dms[i] for i in range(sim.config.sim.nSci): usefulObjects["sci{}Config".format(i)] = sim.config.scis[i] self.kernel.shell.push(usefulObjects) #kernel.shell.push({'foo': 43, 'print_process_id': print_process_id}) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() control = RichIPythonWidget() control.kernel_manager = self.kernel_manager control.kernel_client = self.kernel_client control.exit_requested.connect(self.stop) layout.addWidget(control) self.kernel.shell.ex("") #control.show() #self.kernel.show def stop(self): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() def write(self,message): self.kernel.shell.write(message) self.kernel.shell.ex("")
def __init__(self): RichJupyterWidget.__init__(self) # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() self.kernel_manager = kernel_manager self.kernel_client = kernel_client
class IPythonConsole: def __init__(self, layout, sim, gui): # Create an in-process kernel self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.shell.write("Welcome to AO Sim!\n") config = sim.config #Pass some useful objects to the user usefulObjects = { "sim" : sim, "gui" : gui, "config" : config, "simConfig" : sim.config.sim, "telConfig" : sim.config.tel, "atmosConfig" : sim.config.atmos, "np" : numpy, "plt" : pyplot} for i in range(sim.config.sim.nGS): usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i] for i in range(sim.config.sim.nDM): usefulObjects["dm{}Config".format(i)] = sim.config.dms[i] for i in range(sim.config.sim.nSci): usefulObjects["sci{}Config".format(i)] = sim.config.scis[i] self.kernel.shell.push(usefulObjects) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() control = RichIPythonWidget() control.kernel_manager = self.kernel_manager control.kernel_client = self.kernel_client control.exit_requested.connect(self.stop) layout.addWidget(control) self.kernel.shell.ex("") def stop(self): self.kernel_client.stop_channels() self.kernel_manager.shutdown_kernel() def write(self,message): self.kernel.shell.write(message) self.kernel.shell.ex("")
def __init__(self, *args, **kwargs): """ A constructor matching that of RichJupyterWidget :param args: Positional arguments passed directly to RichJupyterWidget :param kwargs: Keyword arguments. The following keywords are understood by this widget: - banner: Replace the default banner with this text - startup_code: A code snippet to run on startup. It is also added to the banner to inform the user. the rest are passed to RichJupyterWidget """ banner = kwargs.pop("banner", "") startup_code = kwargs.pop("startup_code", "") super(InProcessJupyterConsole, self).__init__(*args, **kwargs) # adjust startup banner accordingly # newer ipython has banner1 & banner2 and not just banner two_ptr_banner = hasattr(self, 'banner1') if not banner: banner = self.banner1 if two_ptr_banner else self.banner if startup_code: banner += "\n" + \ "The following code has been executed at startup:\n\n" + \ startup_code if two_ptr_banner: self.banner1 = banner self.banner2 = '' else: self.banner = banner # create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt' # use a separate thread for execution shell = kernel.shell shell.run_code = async_wrapper(shell.run_code, shell) # attach channels, start kenel and run any startup code kernel_client = kernel_manager.client() kernel_client.start_channels() if startup_code: shell.ex(startup_code) self.kernel_manager = kernel_manager self.kernel_client = kernel_client
def show(): global ipython_widget # Prevent from being garbage collected # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() ipython_widget = RichJupyterWidget() ipython_widget.kernel_manager = kernel_manager ipython_widget.kernel_client = kernel_client ipython_widget.show()
def _setup_kernel(self): """ Setup the kernel for the widget. """ kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel = kernel_manager.kernel kernel.gui = 'qt' kernel_client = kernel_manager.client() kernel_client.start_channels() ipy_widget = self.ipy_widget ipy_widget.kernel_manager = kernel_manager ipy_widget.kernel_client = kernel_client
def terminal_widget(**kwargs): # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push(kwargs) kernel_client = kernel_manager.client() kernel_client.start_channels() control = RichJupyterWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client return control
def __init__(self, *args, **kw): super(IPythonWidget, self).__init__(*args, **kw) # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt' kernel_client = kernel_manager.client() kernel_client.start_channels() self.kernel_manager = kernel_manager self.kernel_client = kernel_client if not in_mantidplot(): self.execute('from mslice.util.mantid.mantid_algorithms import *', hidden=True) self.execute('from mslice.cli import *', hidden=True) else: self.execute('import mslice.cli as mc')
def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.app = app = guisupport.get_app_qt4() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels()
def _load_ipython(self): # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel_manager.kernel.gui = 'qt4' kernel_manager.kernel.shell.enable_pylab(gui='inline') kernel_client = kernel_manager.client() kernel_client.start_channels() control = RichIPythonWidget() self.ipythonDockWidget.setWidget(control) control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(kernel_client.stop_channels) control.exit_requested.connect(kernel_manager.shutdown_kernel) class IPythonNamespaceUpdater(QtCore.QObject): shell = kernel_manager.kernel.shell def eventFilter(self, target, e): if e.type() == QtCore.QEvent.Enter: self.shell.push(globals()) return False control.installEventFilter(IPythonNamespaceUpdater(self)) class Debug(object): def __init__(self, shell): self.shell = shell def __call__(self): import inspect frame = inspect.currentframe() try: temp = frame.f_back.f_globals temp.update(frame.f_back.f_locals) finally: del frame self.shell.run_line_magic('reset', '-f -s') self.shell.push(temp) # now monkeypatch hexrd.debug to use the qt console: hexrd.debug = Debug(kernel_manager.kernel.shell)
class EmbedIPython(RichIPythonWidget): """ Based on: http://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application """ def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.app = app = guisupport.get_app_qt4() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() def get_kernel_shell(self): return self.kernel_manager.kernel.shell def get_kernel_shell_user(self): return self.kernel_manager.kernel.shell.user_ns
def _get_kernel_manager(self): if self._kernel_manager is None: if not JUPYTER_AVAILABLE: raise RuntimeError('Jupyter is not available on this system') # Initializing the kernel self._kernel_manager = QtInProcessKernelManager() self._kernel_manager.start_kernel() self._kernel_manager.kernel.gui = 'qt' # Initializing context self._kernel_manager.kernel.shell.push({x.name : x.object for x in self._get_context()}) return self._kernel_manager
def __init__(self, *args, **kwargs): super(ConsoleWidget, self).__init__(*args, **kwargs) # Create an in-process kernel app = guisupport.get_app_qt4() kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() # Set the kernel data self.kernel = kernel_manager.kernel self.kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() self.kernel_manager = kernel_manager self.kernel_client = kernel_client self.exit_requested.connect(stop)
def embed_ipy(parent, passthrough=None): """ Embed an ipython kernel into the parent widget using a RichJupyterWidget :param parent: Qt Widget to receive the RichJupyterWidget :param passthrough: dict containing variables to pass into scope of the IPython Kernel Use this with caution; strange things can happen if you pass GUI elements to the IPython scope and then call any of their show() or draw() methods. :return: dict with reference to jupyter widget and ipython kernel """ kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() kernel_client.namespace = parent def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() layout = QtGui.QVBoxLayout(parent) widget = RichJupyterWidget(parent=parent) layout.addWidget(widget) widget.kernel_manager = kernel_manager widget.kernel_client = kernel_client widget.exit_requested.connect(stop) ipython_widget = widget ipython_widget.show() kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent}) # pass variables from main GUI environment into IPython Kernel namespace if passthrough is not None: kernel.shell.push(passthrough) # variables stored in this dict are now accessible in the IPython shell return {'widget': widget, 'kernel': kernel}
def __init__(self, parent=None): super(ConsoleWidget, self).__init__() self.variable_list = get_variables() self.vbox = QtGui.QVBoxLayout() self.setLayout(self.vbox) self.kernel_manager = None self.kernel_client = None self.kernel = None self.jupyter_widget = None self.values = [] self.display_plots = [] self.shell_vars = {} self.gm_count = {} self.letters = list(string.ascii_uppercase) self.reserved_words = ['and', 'del', 'from', 'not', 'while', 'as', 'elif', 'global', 'or', 'with', 'assert', 'else', 'if', 'pass', 'yield', 'break', 'except', 'import', 'print', 'class', 'exec', 'in', 'raise', 'continue', 'finally', 'is', 'return', 'def', 'for', 'lambda', 'try'] # Create ipython widget self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.kernel_client.execute("import vcs, cdms2", silent=True) self.jupyter_widget = RichJupyterWidget() self.jupyter_widget.kernel_manager = self.kernel_manager self.jupyter_widget.kernel_client = self.kernel_client self.jupyter_widget.exit_requested.connect(self.stop) self.jupyter_widget.executed.connect(self.codeExecuted) self.original_ns = dict(self.kernel.shell.user_ns) # Push variableList variables self.variable_list.listUpdated.connect(self.updateVariables) self.updateVariables() self.vbox.addWidget(self.jupyter_widget)
def createIPythonKernel(self): """ Create the IPython Kernel """ # Create an in-process kernel self.kernelManager = QtInProcessKernelManager() self.kernelManager.start_kernel() self.kernel = self.kernelManager.kernel self.kernelClient = self.kernelManager.client() self.kernelClient.start_channels() self.kernel.shell.enable_matplotlib(gui='inline') # Load the necessary packages in the embedded kernel cell = "import numpy as np, matplotlib.pyplot as plt, qtpulsar as qp, libfitorbit as lo" self.kernel.shell.run_cell(cell, store_history=False) # Set the in-kernel matplotlib color scheme to black. self.setMplColorScheme('black') # Outside as well (do we need this?) self.kernel.shell.run_cell(constants.matplotlib_rc_cell_black, store_history=False)
def createJupyterKernel(self): """Create and start the embedded Jupyter Kernel""" # Create an in-process kernel self.kernelManager = QtInProcessKernelManager() self.kernelManager.start_kernel() self.kernel = self.kernelManager.kernel # Launch the kernel self.kernelClient = self.kernelManager.client() self.kernelClient.start_channels() # Allow inline matplotlib figures self.kernel.shell.enable_matplotlib(gui='inline') # Load the necessary packages in the embedded kernel # TODO: show this line in a cell of it's own cell = "import numpy as np, matplotlib.pyplot as plt, qtpulsar as qp" self.kernel.shell.run_cell(cell, store_history=False) # Set the in-kernel matplotlib color scheme to black. self.setMplColorScheme('black') # Outside as well (do we need this?) self.kernel.shell.run_cell(constants.matplotlib_rc_cell_black, store_history=False)
class ConsoleManager: def __init__(self, context_provider=None): """ Args: context_provider: A callable that returns a list of InternalObjectDescriptor for variables that will be accessible from the Jupyter console. """ self._kernel_manager = None self._context_provider = context_provider or (lambda: []) self._context = None self._window = None if JUPYTER_AVAILABLE: # This is sort of experimental. Initialization of a kernel manager takes some time, # we don't want to do that in the main thread when the application is running. Do something about it. try: self._kernel_manager = self._get_kernel_manager() except Exception: logger.info('Could not initialize kernel manager', exc_info=True) # noinspection PyUnresolvedReferences def _get_context(self): # See http://ipython.readthedocs.org/en/stable/api/generated/IPython.core.interactiveshell.html if self._context is None: self._context = self._context_provider() try: import matplotlib as mpl import matplotlib.pyplot as plt self._context.append(InternalObjectDescriptor('mpl', mpl, 'Imported module "matplotlib"')) self._context.append(InternalObjectDescriptor('plt', plt, 'Imported module "matplotlib.pyplot"')) except ImportError: pass try: import numpy as np self._context.append(InternalObjectDescriptor('np', np, 'Imported module "numpy"')) except ImportError: pass try: import pylab self._context.append(InternalObjectDescriptor('pylab', pylab, 'Imported module "pylab"')) except ImportError: pass return self._context def _get_kernel_manager(self): if self._kernel_manager is None: if not JUPYTER_AVAILABLE: raise RuntimeError('Jupyter is not available on this system') # Initializing the kernel self._kernel_manager = QtInProcessKernelManager() self._kernel_manager.start_kernel() self._kernel_manager.kernel.gui = 'qt' # Initializing context self._kernel_manager.kernel.shell.push({x.name : x.object for x in self._get_context()}) return self._kernel_manager def _make_banner(self): longest_name = max([len(x.name) for x in self._get_context()]) banner = 'Available entities:\n' for obj in self._context: banner += '\t%- *s -> %s\n' % (longest_name, obj.name, obj.usage_info) banner += 'Pyuavcan docs: http://uavcan.org/Implementations/Pyuavcan\n' banner += 'DSDL reference: http://uavcan.org/Specification/7._List_of_standard_data_types\n' return banner def show_console_window(self, parent): if self._window is None: km = self._get_kernel_manager() banner = self._make_banner() def on_close(): self._window = None self._window = JupyterConsoleWindow(parent, km, banner) self._window.on_close = on_close # TODO: Jupyter takes a long time to start up, which may sometimes interfere with the node. Fix it somehow. # Here, by using the timer we can split the long start-up sequence into two shorter bursts, which kinda helps. # Ideally, the node should be running in a dedicated thread. # noinspection PyCallByClass,PyTypeChecker QTimer.singleShot(50, self._window.show) def close(self): if self._window is not None: self._window.close() self._window = None
def __init__(self, args): """Initializes application""" super(QSceneGraphEditor, self).__init__(args) self._mainWindow = QtGui.QMainWindow() self._editor = QSceneGraphEditorWindow() self._mainWindow.setCentralWidget(self._editor) exitAction = QtGui.QAction('&Exit', self._mainWindow) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self._mainWindow.close) newAction = QtGui.QAction('&New', self._mainWindow) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('Creates a simple default scene') newAction.triggered.connect(self._editor.new) openAction = QtGui.QAction('&Open...', self._mainWindow) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open scene graph from file') openAction.triggered.connect(self._editor.open) saveAction = QtGui.QAction('&Save', self._mainWindow) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save scene graph') saveAction.triggered.connect(self._editor.save) saveAsAction = QtGui.QAction('&Save As...', self._mainWindow) saveAsAction.setStatusTip('Save scene graph to another file') saveAsAction.triggered.connect(self._editor.saveAs) insertObjectAction = QtGui.QAction('&Insert...', self._mainWindow) insertObjectAction.setShortcut('Ctrl+I') insertObjectAction.setStatusTip('Inserts new scene object before current one') insertObjectAction.triggered.connect(self._editor.inspectorWidget.insertObject) appendObjectAction = QtGui.QAction('&Append...', self._mainWindow) appendObjectAction.setShortcut('Ctrl+K') appendObjectAction.setStatusTip('Inserts new scene object after current one') appendObjectAction.triggered.connect(self._editor.inspectorWidget.appendObject) deleteObjectAction = QtGui.QAction('&Delete', self._mainWindow) deleteObjectAction.setShortcut('DEL') deleteObjectAction.setStatusTip('Deletes currently selected scene object') deleteObjectAction.triggered.connect(self._editor.inspectorWidget.deleteObject) refreshObjectAction = QtGui.QAction('&Refresh', self._mainWindow) refreshObjectAction.setShortcut('F5') refreshObjectAction.setStatusTip('Recreates tree view from root node') refreshObjectAction.triggered.connect(self._editor.refresh) viewAllAction = QtGui.QAction('View &All', self._mainWindow) viewAllAction.setShortcut('Ctrl+A') viewAllAction.setStatusTip('Resets camera in scene so all object are visible') viewAllAction.triggered.connect(self._editor.previewWidget.sceneManager.view_all) viewManipAction = QtGui.QAction('Camera &Manipulation', self._mainWindow) viewManipAction.setShortcut('Ctrl+M') viewManipAction.setStatusTip('Enables manipulation of camera in the scene') viewManipAction.setCheckable(True) viewManipAction.setChecked(True) viewManipAction.connect(QtCore.SIGNAL("triggered(bool)"), self._editor.previewWidget.sceneManager.interaction) self._editor.previewWidget.sceneManager.interaction(True) #self._mainWindow.statusBar() menubar = self._mainWindow.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(newAction) fileMenu.addAction(openAction) fileMenu.addAction(saveAction) fileMenu.addAction(saveAsAction) fileMenu.addSeparator() fileMenu.addAction(exitAction) objectsMenu = menubar.addMenu('&Scene Object') objectsMenu.addAction(insertObjectAction) objectsMenu.addAction(appendObjectAction) objectsMenu.addAction(deleteObjectAction) objectsMenu.addSeparator() objectsMenu.addAction(refreshObjectAction) viewMenu = menubar.addMenu('&View') viewMenu.addAction(viewAllAction) viewMenu.addAction(viewManipAction) if "--console" in self.arguments() or "--ipython" in self.arguments(): # start with IPython console at bottom of application from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager import inventor # Create an in-process kernel kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push({'iv': inventor, 'root': self._editor._root, 'view': self._editor.previewWidget.sceneManager }) kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() self.exit() control = RichJupyterWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.font = QtGui.QFont(control.font.family(), 10); self.addVerticalWidget(control) # load default scene or from file if argument is given file = "#Inventor V2.1 ascii\n\nSeparator { " \ "DirectionalLight {} OrthographicCamera { position 0 0 5 height 5 }" \ "TrackballManip {} Material { diffuseColor 1 0 0 }" \ "Cone {} }" if (len(self.arguments()) > 1) and ("." in self.arguments()[-1]): extension = self.arguments()[-1].split('.')[-1].lower() if extension in [ 'iv', 'vrml', '3ds', 'stl' ]: file = self.arguments()[-1]; self._editor.load(file)