示例#1
0
def main():
    # Print the ID of the main process
    print_process_id()

    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)
示例#2
0
def main():
    """Start kernel manager and client, create window, run app event loop"""
    app = guisupport.get_app_qt4()

    if INPROCESS:
        from IPython.qt.inprocess import QtInProcessKernelManager
        km = QtInProcessKernelManager()
    else:
        from IPython.qt.manager import QtKernelManager
        km = QtKernelManager()
    km.start_kernel()
    km.kernel.gui = 'qt4'
    kc = km.client()
    kc.start_channels()

    widget = RichIPythonWidget()
    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)
示例#3
0
def shell(kernel_manager, kernel_client):
    widget = RichIPythonWidget()
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    widget.setWindowTitle("IPython shell")
    return widget
示例#4
0
def embed_shell_widget( parent_ptr ):
    '''
    Create a RichIPythonWidget as a child of the given parent QWidget.

    Parent is assumed to be an integer and is wrapped into a QWidget using sip.

    This function may only be called when init_embedded_python() previously
    returned True.  It may throw an ImportError if sip or PyQt4 is missing.
    If it successfully returns, the widget was successfully embedded.
    '''
    global _kmgr, _kclient, widget
    if( _kmgr is None ):
        raise RuntimeError( "Kernel manager not initialized!" )
    #print "embedding interactive python widget", parent_ptr, type(parent_ptr)
    import IPython
    from IPython.lib import guisupport
    if IPython.version_info[0] < 4:
        from IPython.qt.console.rich_ipython_widget import RichIPythonWidget as RichWidget
    else:
        from qtconsole.rich_jupyter_widget import RichJupyterWidget as RichWidget
    import sip
    from PyQt4 import QtGui, QtCore

    # Wave the magic wand and turn an integer into a QWidget object.
    parent = sip.wrapinstance(parent_ptr, QtGui.QWidget)

    widget = RichWidget(parent=parent, local_kernel=True)
    widget.kernel_manager = _kmgr
    widget.kernel_client = _kclient
    parent.layout().addWidget(widget)
    widget.change_font_size(-2)
    import __main__
    __main__.ipw = widget
def main():
    # Print the ID of the main process
    print_process_id()

    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 = QtAsyncInProcessKernelManager()
    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)
示例#6
0
def show_ipython_console():
    # from https://github.com/ipython/ipython/blob/1.x/examples/inprocess/embedded_qtconsole.py
    # this might be able to be a dockable panel at some point in the future.
    # it should also only allow one window open at a time - I think it steals stdout at start
    # and opening a new window stops output working on the old one!
    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_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)
def main():

    #LETS ALSO DO SOME IPYTHOPN PARRALLEL STUFF

    global splicer
    app = guisupport.get_app_qt4()
    from LZM100 import splicer
    # 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({'splicer': splicer})

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

    #app = QtGui.QApplication(sys.argv)
    #ex = Example()
    b = TaperDesign(Taper())
    sys.exit(app.exec_())
示例#8
0
def show_ipython_console():
    # from https://github.com/ipython/ipython/blob/1.x/examples/inprocess/embedded_qtconsole.py
    # this might be able to be a dockable panel at some point in the future.
    # it should also only allow one window open at a time - I think it steals stdout at start
    # and opening a new window stops output working on the old one!
    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_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)
示例#9
0
文件: main.py 项目: beamteamco/hexrd
    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)
示例#10
0
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 = RichIPythonWidget()
    control.kernel_manager = kernel_manager
    control.kernel_client = kernel_client
    return control
示例#11
0
文件: main.py 项目: lind9/hexrd
    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)
    def __init__(self,partent):
        kernel_manager=QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel=kernel_manager.kernel
        kernel.gui ='qt'

        kernel_client=kernel_manager.client()
        kernel_client.start_channels()

        QtGui.QWidget.__init__(self)
        displayname=QtGui.QLabel('iPython Terminal Widget')
        mainlayout=QtGui.QGridLayout(self)
#        console=IPythonWidget(self)
        console=RichIPythonWidget(self)
        console.kernel_manager=kernel_manager
        console.kernel_client=kernel_client
        console.exit_requested.connect(self.stop)

        mainlayout.addWidget(console,0,0)
示例#13
0
    def __init__(self, partent):
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        QtGui.QWidget.__init__(self)
        displayname = QtGui.QLabel('iPython Terminal Widget')
        mainlayout = QtGui.QGridLayout(self)
        #        console=IPythonWidget(self)
        console = RichIPythonWidget(self)
        console.kernel_manager = kernel_manager
        console.kernel_client = kernel_client
        console.exit_requested.connect(self.stop)

        mainlayout.addWidget(console, 0, 0)
示例#14
0
def console(client, args):

	local = {
		'client': client,
		'auth': client.auth,
		'reset': client.reset,
		'config': client.config,
		'execute': client.execute,
	}

	if args['scriptName']:
		#############################################################
		# EXECUTE FILE                                              #
		#############################################################

		sys.argv = []
		sys.argv.append(args['scriptName'])
		sys.argv.extend(args['scriptArgs'])

		try:
			f = open(sys.argv[0])
			source_code = f.read()
			f.close()

		except IOError as e:
			raise pyAMI.exception.Error(e)

		compiled_code = compile(source_code, sys.argv[0], 'exec')

		safe_exec(compiled_code, globals(), local)

		#############################################################

	else:
		#############################################################
		# RUN CONSOLE                                               #
		#############################################################

		sys.argv = [sys.argv[0]]

		#############################################################

		banner = pyAMI.config.banner if args['nosplash'] == False else ''

		#############################################################

		if args['gIPython']:
			#####################################################
			# IPYTHON GRAPHICAL MODE                            #
			#####################################################

			try:
				from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
				from IPython.qt.inprocess import QtInProcessKernelManager
				from IPython.lib import guisupport

			except ImportError as e:
				raise pyAMI.exception.Error('module `IPython` not properly installed: %s' % e)

			################################
			# HACK IPYTHON BANNER          #
			################################

			RichIPythonWidget._banner_default = lambda self: banner

			################################
			# KERNEL_MANAGER               #
			################################

			kernel_manager = QtInProcessKernelManager()
			kernel_manager.start_kernel()

			################################
			# KERNEL_CLIENT                #
			################################

			kernel_client = kernel_manager.client()
			kernel_client.start_channels()

			################################
			# PYAMI                        #
			################################

			kernel_manager.kernel.shell.push(local)

			################################
			# APPLICATION                  #
			################################

			a = guisupport.get_app_qt4()

			def stop():
				kernel_client.stop_channels()
				kernel_manager.shutdown_kernel()
				a.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(a)

			#####################################################

		elif args['cIPython']:
			#####################################################
			# IPYTHON CONSOLE MODE                              #
			#####################################################

			try:
				from IPython.terminal.embed import InteractiveShellEmbed

			except ImportError as e:
				raise pyAMI.exception.Error('module `IPython` not properly installed: %s' % e)

			################################
			# SHELL                        #
			################################

			shell = InteractiveShellEmbed(banner1 = banner, banner2 = None)

			shell(local_ns = local)

			#####################################################

		else:
			#####################################################
			# DEFAULT MODE                                      #
			#####################################################

			code.interact(banner = banner, local = local)

			#####################################################

	return 0
示例#15
0
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()
示例#16
0
def procsteppython_do_run(stepglobals, runfunc, argkw, ipythonmodelist, action,
                          scripthref, pycode_text, pycode_lineno):

    if not ipythonmodelist[0]:
        resultdict = runfunc(**argkw)
        return resultdict
    else:
        # ipython mode
        # in-process kernel, a-la https://raw.githubusercontent.com/ipython/ipython/master/examples/Embedding/inprocess_qtconsole.py

        ## Set PyQt4 API version to 2 and import it -- required for ipython compatibility
        #import sip
        #sip.setapi('QVariant', 2)
        #sip.setapi('QString', 2)
        #sip.setapi('QDateTime', 2)
        #sip.setapi('QDate', 2)
        #sip.setapi('QTextStream', 2)
        #sip.setapi('QTime', 2)
        #sip.setapi('QUrl', 2)
        #from PyQt4 import QtGui   # force IPython to use PyQt4 by importing it first

        # RHEL6 compatibility  -- if running under Python 2.6, just import IPython, get PyQt4
        if sys.version_info < (2, 7):
            from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
            from IPython.qt.inprocess import QtInProcessKernelManager
            pass
        else:

            # Under more recent OS's: Make matplotlib use PySide
            # http://stackoverflow.com/questions/6723527/getting-pyside-to-work-with-matplotlib
            import matplotlib
            matplotlib.use('Qt4Agg')
            matplotlib.rcParams['backend.qt4'] = 'PySide'
            pass

        import IPython
        from IPython.core.interactiveshell import DummyMod

        if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'):
            # Recent Jupyter/ipython: Import from qtconsole
            # Force PySide bindings
            import PySide.QtCore
            from qtconsole.qt import QtGui
            from qtconsole.inprocess import QtInProcessKernelManager

            # Obtain the running QApplication instance
            app = QtGui.QApplication.instance()
            if app is None:
                # Start our own if necessary
                app = QtGui.QApplication([])
                pass

            pass
        else:
            from IPython.qt.inprocess import QtInProcessKernelManager
            from IPython.lib import guisupport
            app = guisupport.get_app_qt4()

            pass

        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt4'

        #sys.stderr.write("id(stepglobals)=%d" % (id(stepglobals)))

        # Make ipython use our globals as its global dictionary
        # ... but first keep a backup
        stepglobalsbackup = copy.copy(stepglobals)

        (kernel.user_module,
         kernel.user_ns) = kernel.shell.prepare_user_module(
             user_ns=stepglobals)

        # Should we attempt to run the function here?

        # (gui, backend) = kernel.shell.enable_matplotlib("qt4") #,import_all=False) # (args.gui, import_all=import_all)
        (gui, backend, clobbered) = kernel.shell.enable_pylab(
            "qt4", import_all=False)  # (args.gui, import_all=import_all)

        # kernel.shell.push(stepglobals) # provide globals as variables -- no longer necessary as it's using our namespace already

        kernel.shell.push(argkw)  # provide arguments as variables

        kernel.shell.push(
            {"kernel": kernel},
            interactive=False)  # provide kernel for debugging purposes

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        abort_requested_list = [False
                                ]  # encapsulated in a list to make it mutable

        def stop():
            control.hide()
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            app.exit()
            pass

        def abort():
            # simple exit doesn't work. See http://stackoverflow.com/questions/1527689/exit-from-ipython
            # too bad this doesn't work right now!!!
            class Quitter(object):
                def __repr__(self):
                    sys.exit()

                pass

            kernel.shell.push({"quitter": Quitter()})
            kernel.shell.ex("quitter")

            stop()
            abort_requested_list.pop()
            abort_requested_list.append(True)
            pass

        if pycode_text is None:
            kernel.shell.write("\n\nExecute %s/%s\n" %
                               (scripthref.getpath(), runfunc.__name__))
            pass
        else:
            kernel.shell.write(
                "\n\nExecute %s/%s/%s\n" %
                (scripthref.getpath(), action, runfunc.__name__))
            pass

        kernel.shell.write("Assign return value to \"ret\" and press Ctrl-D\n")
        kernel.shell.write("Set cont=True to disable interactive mode\n")
        # kernel.shell.write("call abort() to exit\n")

        if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'):
            # Recent Jupyter/ipython: Import from qtconsole
            from qtconsole.rich_jupyter_widget import RichJupyterWidget as RichIPythonWidget
            pass
        else:
            from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
            pass

        control = RichIPythonWidget()
        control.kernel_manager = kernel_manager
        control.kernel_client = kernel_client
        control.exit_requested.connect(stop)
        control.show()

        #sys.stderr.write("lines=%s\n" % (str(lines)))
        #sys.stderr.write("lines[0]=%s\n" % (str(lines[0])))

        try:
            if pycode_text is None:
                (lines, startinglineno) = inspect.getsourcelines(runfunc)

                assert (lines[0].startswith("def")
                        )  # first line of function is the defining line
                del lines[0]  # remove def line
                lines.insert(0, "if 1:\n")  # allow function to be indented
                runfunc_syntaxtree = ast.parse(
                    "".join(lines), filename=scripthref.getpath(), mode='exec'
                )  # BUG: Should set dont_inherit parameter and properly determine which __future__ import flags should be passed

                # fixup line numbers
                for syntreenode in ast.walk(runfunc_syntaxtree):
                    if hasattr(syntreenode, "lineno"):
                        syntreenode.lineno += startinglineno - 1
                        pass
                    pass

                # runfunc_syntaxtree should consist of the if statement we just added
                # use _fields attribute to look up fields of an AST element
                # (e.g. test, body, orelse for IF)
                # then those fields can be accessed directly
                assert (len(runfunc_syntaxtree.body) == 1)
                code_container = runfunc_syntaxtree.body[0]
                assert (isinstance(code_container, ast.If)
                        )  # code_container is the if statement we just wrote

                kernel.shell.push(
                    {"runfunc_syntaxtree": runfunc_syntaxtree},
                    interactive=False
                )  # provide processed syntax tree for debugging purposes

                pass
            else:
                fullsyntaxtree = ast.parse(
                    pycode_text
                )  # BUG: Should set dont_inherit parameter and properly determine which __future__ import flags should be passed
                # fixup line numbers
                for syntreenode in ast.walk(fullsyntaxtree):
                    if hasattr(syntreenode, "lineno"):
                        syntreenode.lineno += pycode_lineno - 1
                        pass
                    pass
                code_container = None
                for codeelement in fullsyntaxtree.body:
                    if isinstance(codeelement, ast.FunctionDef):
                        if codeelement.name == runfunc.__name__:
                            code_container = codeelement
                            runfunc_syntaxtree = codeelement
                            pass
                        pass

                    pass
                if code_container is None:
                    raise ValueError(
                        "Couldn't find code for %s for ipython execution" %
                        (runfunc.__name__))

                kernel.shell.push(
                    {"fullsyntaxtree": fullsyntaxtree}, interactive=False
                )  # provide full syntax tree for debugging purposes

                pass

            # identify global variables from runfunc_syntaxtree
            globalvars = set()
            for treeelem in ast.walk(runfunc_syntaxtree):
                if isinstance(treeelem, ast.Global):
                    globalvars = globalvars.union(treeelem.names)
                    pass
                pass

            kernel.shell.push({"abort": abort})  # provide abort function
            kernel.shell.push({"cont": False})  # continue defaults to False

            returnstatement = code_container.body[-1]
            if isinstance(returnstatement, ast.Return):
                # last statement is a return statement!
                # Create assign statement that assigns
                # the result to ret
                retassign = ast.Assign(targets=[
                    ast.Name(id="ret",
                             ctx=ast.Store(),
                             lineno=returnstatement.lineno,
                             col_offset=returnstatement.col_offset)
                ],
                                       value=returnstatement.value,
                                       lineno=returnstatement.lineno,
                                       col_offset=returnstatement.col_offset)
                del code_container.body[-1]  # remove returnstatement
                code_container.body.append(retassign)  # add assignment
                pass

            runfunc_lines = code_container.body

            kernel.shell.push(
                {
                    "runfunc_lines": runfunc_lines,
                    "scripthref": scripthref
                },
                interactive=False
            )  # provide processed syntax tree for debugging purposes

            # kernel.shell.run_code(compile("kernel.shell.run_ast_nodes(runfunc_lines,scriptpath,interactivity='all')","None","exec"))
            if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'):
                # Recent Jupyter/ipython: Import from qtconsole
                from qtconsole.inprocess import QtCore
                pass
            else:
                from IPython.qt.inprocess import QtCore
                pass
            QTimer = QtCore.QTimer

            def showret():
                control.execute("ret")
                pass

            def runcode():
                control.execute(
                    "kernel.shell.run_ast_nodes(runfunc_lines,scripthref.getpath(),interactivity='none')"
                )
                # QTimer.singleShot(25,showret) # get callback 25ms into main loop
                # showret disabled because it prevents you from running the
                # debugger in post-mortem mode to troubleshoot an exception:
                # import pdb; pdb.pm()
                pass

            QTimer.singleShot(25, runcode)  # get callback 25ms into main loop
            # control.execute("kernel.shell.run_ast_nodes(runfunc_lines,scripthref.getpath(),interactivity='none')")

            pass
        except:
            (exctype, excvalue) = sys.exc_info()[:2]
            sys.stderr.write(
                "%s while attempting to prepare URL %s code for interactive execution: %s\n"
                % (exctype.__name__, scripthref.absurl(), str(excvalue)))
            traceback.print_exc()
            raise

        if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'):
            # Recent Jupyter/ipython: Import from qtconsole
            app.exec_()
            pass
        else:
            # Old ipython
            guisupport.start_event_loop_qt4(app)
            pass

        if abort_requested_list[0]:
            pass

        if kernel.shell.ev("cont"):
            # cont==True -> disable interactive mode
            ipythonmodelist.pop()
            ipythonmodelist.append(False)
            pass

        try:
            retval = kernel.shell.ev(
                "ret")  # Assign result dictionary to "ret" variable
            pass
        except NameError:  # if ret not assigned, return {}
            retval = {}
            pass

        # Performing this execution changed values in stepglobals
        # but it should have only done that for variables specified
        # as 'global' in the function.

        # So: Update our backup of the value of stepglobals,
        #     according to the specified globals, and
        #     replace stepglobals with that updated backup

        stepglobalsbackup.update(
            dict([(varname, stepglobals[varname]) for varname in globalvars]))
        stepglobals.clear()
        stepglobals.update(stepglobalsbackup)

        return retval

    pass
示例#17
0
    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 "--ipython" in self.arguments():
            # start with IPython console at bottom of application
            from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
            from IPython.qt.inprocess import QtInProcessKernelManager
            from IPython.lib import guisupport
            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 = RichIPythonWidget()
            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)