def setUpClass(cls):
     """ Create the application for the test case.
     """
     cls._app = QtGui.QApplication.instance()
     if cls._app is None:
         cls._app = QtGui.QApplication([])
     cls._app.setQuitOnLastWindowClosed(False)
示例#2
0
def main():

    print_process_id()

    app = QtGui.QApplication([])

    widget = ConsoleWidget()

    monokai = qtconsole.styles.default_dark_style_sheet
    widget.style_sheet = monokai

    widget.execute_command("%run -m src.loadenv")
    widget.execute_command("%matplotlib inline\n")
    """
    instructions = "{}{}{}{}".format(
        "Check 'ghargs': ",
        str(sys.argv[1]) if len(sys.argv)>1 else "Null",
        "%run -m src.openstudio_python $osmfile\n",
        "PID: "+str(os.getpid())
        )
    """
    #widget.print_text(instructions)
    widget.show()

    app.exec_()
示例#3
0
文件: qtip.py 项目: kstovall/qtip
def main():
    # The option parser
    usage = "usage: %prog [options]"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option('-f', '--file', action='store', type='string', nargs=2, \
            default=(None, None), help="Provide a parfile and a timfile")

    parser.add_option('-p', '--periodfile', action='store', type='string', nargs=1, \
            default=(None, None), help="Provide a period file (per)")

    parser.add_option('-e', '--engine', action='store', type='string', nargs=1, \
            default='pint', \
            help="Pulsar timing engine: libstempo/pint")

    (options, args) = parser.parse_args()

    # Create the application
    app = QtGui.QApplication(sys.argv)

    # Create the window, and start the application
    qtipwin = QtipWindow(engine=options.engine, \
            parfile=options.file[0], timfile=options.file[1],\
            perfile=options.periodfile[0])
    qtipwin.raise_()        # Required on OSX to move the app to the foreground
    sys.exit(app.exec_())
示例#4
0
def main():
    """Invoke GUI application."""
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    app = QtGui.QApplication(sys.argv)
    ns = {}
    ns['exit'] = sys.exit
    window = MainWindow(ns)

    logging.basicConfig(level=logging.INFO)

    window.show()
    app.exec_()
示例#5
0
文件: qtip.py 项目: jcolen/qtiPINT
def main():
    # The option parser
    usage = "usage: %prog [options]"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option('-p', '--parfile', action='store', type='string', nargs=1, \
            default=None, help="provide a parfile")
    parser.add_option('-t', '--timfile', action='store', type='string', nargs=1, \
            default=None, help="provide a timfile")

    (options, args) = parser.parse_args()

    # Create the application
    app = QtGui.QApplication(sys.argv)

    # Create the window, and start the application
    qtipwin = QtipWindow(parfile=options.parfile, timfile=options.timfile)
    qtipwin.raise_()  # Required on OSX to move the app to the foreground
    sys.exit(app.exec_())
示例#6
0
    def _run_embedded_qtconsole(conn_filename):
        # This is launched as a new process.
        #
        # Wait max. ten seconds for the IPython kernel to be up and running,
        # which is done by checking for presence of the connection file
        # containing the kernels Zero Message Queue sockets and credentials.
        #
        # Then, start a new QApplication running the Jupyter Console client
        # widget connected to the kernel via the connection file.
        #
        for i in range(100):
            try:
                st = os.stat(conn_filename)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    # No such file exception is ignored, all others re-raised
                    raise
            else:
                if st.st_size > 0:
                    # OK, connection file found, kernel seems to be running
                    break
            time.sleep(0.1)

        app = QtGui.QApplication(["Plot Workbench Console"])

        kernel_client = QtKernelClient(connection_file=conn_filename)
        kernel_client.load_connection_file()
        kernel_client.start_channels()

        def exit():
            kernel_client.shutdown()
            kernel_client.stop_channels()
            app.exit()

        ipython_widget = RichJupyterWidget()
        ipython_widget.kernel_client = kernel_client
        ipython_widget.exit_requested.connect(exit)
        ipython_widget.show()

        app.exec_()
示例#7
0
def main():
    usage, description = __doc__.split('\n\n', 1)
    parser = optparse.OptionParser(usage=usage, description=description)

    parser.add_option('--serial', '-s', default='/dev/ttyACM0')
    parser.add_option('--baudrate', '-b', type='int', default=115200)
    parser.add_option('--devices', '-d', type='str', default='1')
    parser.add_option('--target', '-t', default=None)
    parser.add_option('--rs485', '-c', action='store_true')
    parser.add_option('--max-receive-bytes', default=127, type=int)

    options, args = parser.parse_args()
    assert len(args) == 0

    app = QtGui.QApplication(sys.argv)

    # To work around https://bugreports.qt.io/browse/PYSIDE-88
    app.aboutToQuit.connect(lambda: os._exit(0))

    tv = TviewMainWindow(options)
    tv.show()

    app.exec_()
示例#8
0
        """
        self.kernel_manager.kernel.shell.push(variableDict)

    def clear(self):
        """
        Clears the terminal
        """
        self._control.clear()

        # self.kernel_manager

    def print_text(self, text):
        """
        Prints some plain text to the console
        """
        self._append_plain_text(text)

    def execute_command(self, command):
        """
        Execute a command in the frame of the console widget
        """
        self._execute(command, False)


if __name__ == '__main__':

    app = QtGui.QApplication([])
    widget = ConsoleWidget()
    widget.show()
    app.exec_()
示例#9
0
 def init_qt_app(self):
     # separate from qt_elements, because it must run first
     self.app = QtGui.QApplication(['jupyter-qtconsole'])
     self.app.setApplicationName('jupyter-qtconsole')
示例#10
0
 def init_qt_app(self):
     # separate from qt_elements, because it must run first
     self.app = QtGui.QApplication([])
def main():
    app = QtGui.QApplication(sys.argv)
    tool = CityscapesViewer()
    sys.exit(app.exec_())
示例#12
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