Exemple #1
0
def console_widget(manager):
    try: # Ipython v0.13
        widget = RichIPythonWidget(gui_completion='droplist')
    except TraitError:  # IPython v0.12
        widget = RichIPythonWidget(gui_completion=True)
    widget.kernel_manager = manager
    return widget
Exemple #2
0
 def __init__(self, *args, **kwargs):
     """Constructor"""
     
     RichIPythonWidget.__init__(self, *args, **kwargs)
     self._existing = True
     self._may_close = False
     self._confirm_exit = False
Exemple #3
0
 def __init__(self, parent):
   from logging import getLogger, CRITICAL
   logger=getLogger()
   silenced=None
   for handler in logger.handlers:
     if handler.__class__.__name__=='QtHandler':
       silenced=handler
       old_level=silenced.level
       silenced.setLevel(CRITICAL+1)
       break
   RichIPythonWidget.__init__(self)
   self._parent=parent
   self.buffer_size=10000 # increase buffer size to show longer outputs
   self.set_default_style(colors='linux')
   if IPython.__version__<'1.0':
     kernelapp=IPythonLocalKernelApp.instance()
     kernelapp.initialize()
     self.connect_kernel(connection_file=kernelapp.get_connection_file())
   else:
     kernel_manager=QtInProcessKernelManager(config=self.config, gui='qt4')
     kernel_manager.start_kernel()
     self.kernel_manager=kernel_manager
     self.kernel_client=kernel_manager.client()
     self.kernel_client.start_channels()
   ip=get_ipython()
   # console process exceptions (IPython controlled)
   ip.set_custom_exc((Exception,), ip_excepthook_overwrite)
   self.namespace=ip.user_ns
   self.namespace['IP']=self
   self.namespace['app']=QtGui.QApplication.instance()
   self.namespace['gui']=parent
   self.namespace['plot']=self._plot
   if silenced:
     silenced.setLevel(old_level)
Exemple #4
0
def console_widget(manager):
    try:  # Ipython v0.13
        widget = RichIPythonWidget(gui_completion='droplist')
    except TraitError:  # IPython v0.12
        widget = RichIPythonWidget(gui_completion=True)
    widget.kernel_manager = manager
    return widget
            def get_widget(self, droplist_completion=True):
                completion = 'droplist' if droplist_completion else 'plain'
                widget = RichIPythonWidget(gui_completion=completion)
                widget.kernel_manager = self.kernel_manager
                widget.kernel_client = self.kernel_client

                return widget
Exemple #6
0
    def __init__(self, *args, **kwargs):
        """Constructor"""

        RichIPythonWidget.__init__(self, *args, **kwargs)
        self._existing = True
        self._may_close = False
        self._confirm_exit = False
def main():
    app = qapplication()
    mainwin = MainWindow()

    shell = RichIPythonWidget(local_kernel=False)
    shell.kernel_manager = init_kernel_manager()
    mainwin.insertPythonShell(shell)
    
    mainwin.show()
    app.exec_()
def terminal_widget(parent=None, **kwargs):
    kernel_app = default_kernel_app()
    manager = default_manager(kernel_app)
    widget = RichIPythonWidget(parent=parent, gui_completion='droplist')
    widget.kernel_manager = manager

    #update namespace
    kernel_app.shell.user_ns.update(kwargs)
    kernel_app.shell.user_ns['console'] = widget
    kernel_app.shell.run_cell(
        'print("\\nAvailable variables are everything from pylab, “{}”, and this console as “console”")'
        .format('”, “'.join(kwargs.keys())))

    kernel_app.start()
    return widget
        def get_widget(self, droplist_completion=True):
            if IPython.__version__ < '0.13':
                completion = droplist_completion
            else:
                completion = 'droplist' if droplist_completion else 'plain'
            widget = RichIPythonWidget(gui_completion=completion)

            cf = find_connection_file(self.kernel_app.connection_file)
            km = QtKernelManager(connection_file=cf, config=widget.config)
            km.load_connection_file()
            km.start_channels()
            widget.kernel_manager = km
            atexit.register(km.cleanup_connection_file)

            sys.stdout = self._stdout
            sys.stderr = self._stderr
            sys.displayhook = self._dishook

            return widget
Exemple #10
0
def _glue_terminal_1(**kwargs):
    """ Used for IPython v0.13, v0.12
    """
    kernel_app = default_kernel_app()
    manager = default_manager(kernel_app)

    try:  # IPython v0.13
        widget = RichIPythonWidget(gui_completion='droplist')
    except TraitError:  # IPython v0.12
        widget = RichIPythonWidget(gui_completion=True)
    widget.kernel_manager = manager

    # update namespace
    kernel_app.shell.user_ns.update(kwargs)

    # for debugging
    kernel_app.shell.user_ns['_kernel'] = kernel_app
    kernel_app.shell.user_ns['_manager'] = manager
    kernel_app.shell.user_ns['_widget'] = glue_terminal

    return 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 = 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)
Exemple #12
0
def make_terminal_widget(parent=None, **base_ns):
    try:
        gui_completion = _GUI_COMPLETION_CONVERT[kate.configuration[_GUI_COMPLETION_TYPE_CFG]]
    except KeyError:
        gui_completion = 'droplist'
    if gui_completion:
        widget = RichIPythonWidget(parent=parent, gui_completion=gui_completion)
    else:
        widget = RichIPythonWidget(parent=parent)

    widget.banner += i18n('\nAvailable variables are everything from pylab, “%1”, and this console as “console”', '”, “'.join(base_ns.keys()))

    client, manager, shell = init_ipython()

    # https://github.com/ipython/ipython/blob/master/examples/inprocess/embedded_qtconsole.py
    if ipython_1:
        widget.kernel_client = client

        widget.exit_requested.connect(widget.kernel_client.stop_channels)
        widget.exit_requested.connect(manager.shutdown_kernel)
    else:
        widget.exit_requested.connect(manager.cleanup_connection_file)

    widget.kernel_manager = manager

    base_ns['console'] = widget
    shell.user_ns.update(base_ns)

    try:
        projectPlugin = get_project_plugin()
    except AttributeError:
        projectPlugin = None
    if projectPlugin:
        def project_changed(*args, **kwargs):
            reset_shell(shell, base_ns)
        projectPlugin.projectFileNameChanged.connect(project_changed)
        project_changed()

    sys.stdout.flush()
    return widget
def main():
    app = guisupport.get_app_qt4()

    # Create a kernel. 
    #
    # Setting the GUI is not necessary for the normal operation of the kernel,
    # but it is used for IPython GUI's integration, particularly in pylab. By
    # default, the inline backend is used, which is safe under all toolkits.
    #
    # WARNING: Under no circumstances should another GUI toolkit, like wx, be
    # used when running a Qt application. This will lead to unexpected behavior,
    # including segfaults.
    kernel = InProcessKernel(gui='qt4')

    # Populate the kernel's namespace.
    kernel.shell.push({'x': 0, 'y': 1, 'z': 2})

    # Create a kernel manager for the frontend and register it with the kernel.
    km = QtInProcessKernelManager(kernel=kernel)
    km.start_channels()
    kernel.frontends.append(km)

    # Create the Qt console frontend.
    control = RichIPythonWidget()
    control.exit_requested.connect(app.quit)
    control.kernel_manager = km
    control.show()

    # Execute some code directly. Note where the output appears.
    kernel.shell.run_cell('print "x=%r, y=%r, z=%r" % (x,y,z)')

    # Execute some code through the frontend (once the event loop is
    # running). Again, note where the output appears.
    do_later(control.execute, '%who')

    guisupport.start_event_loop_qt4(app)
Exemple #14
0
    def __init__(self, app, imports=None, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.app = app
        qtapp = self.app.getApp()
        kernel = InProcessKernel(gui='qt5')
        self.kernel = kernel
        self.shell = kernel.shell

        # Populate the kernel's namespace.
        kernel.shell.push({'api': self.app.api, 'self': self.app, 'shell': kernel.shell})

        for plugin in self.app.pm.plugins:
            self.shell.push({plugin.name: plugin})

        self.push = kernel.shell.push
        self.ex = kernel.shell.ex


        # Create a kernel manager for the frontend and register it with the kernel.
        km = QtInProcessKernelManager(kernel=kernel)
        km.start_channels()
        kernel.frontends.append(km)

        # Create the Qt console frontend.
        control = RichIPythonWidget()
        control.exit_requested.connect(qtapp.quit)
        control.kernel_manager = km
        control.show()

        self.widget = control

        self.imports = [
            'from PyQt4.QtCore import *',
            'from PyQt4.QtGui import *',
            'import json',
            'import os, sys'
        ]
        if imports is not None and type(imports) is list:
            self.imports.extend(imports)
        for import_line in self.imports:
            kernel.shell.ex(import_line)



        self.setLayout(QVBoxLayout())
        self.layout().addWidget(control)
#        self.addTab(control, 'Main')

        control.clear()

        self.app.api.echo = self.echo
        self.app.api.echoServerOutput = self.echoServerOutput
        self.app.api.setIPInput = self.set_input
        self.app.api.pushToIP = self.shell.push
        self.app.api.setIPCursor = self.setCursorPos
Exemple #15
0
 def __init__(self, *args, **kw):
     RichIPythonWidget.__init__(self, *args, **kw)
     self._existing = True
     self._may_close = False
     self._confirm_exit = False
Exemple #16
0
def main():
    """ Entry point for application.
    """
    # Parse command line arguments.
    parser = ArgumentParser()
    kgroup = parser.add_argument_group('kernel options')
    kgroup.add_argument('-e',
                        '--existing',
                        action='store_true',
                        help='connect to an existing kernel')
    kgroup.add_argument(
        '--ip',
        type=str,
        default=LOCALHOST,
        help='set the kernel\'s IP address [default localhost]')
    kgroup.add_argument('--xreq',
                        type=int,
                        metavar='PORT',
                        default=0,
                        help='set the XREQ channel port [default random]')
    kgroup.add_argument('--sub',
                        type=int,
                        metavar='PORT',
                        default=0,
                        help='set the SUB channel port [default random]')
    kgroup.add_argument('--rep',
                        type=int,
                        metavar='PORT',
                        default=0,
                        help='set the REP channel port [default random]')
    kgroup.add_argument('--hb',
                        type=int,
                        metavar='PORT',
                        default=0,
                        help='set the heartbeat port [default: random]')

    egroup = kgroup.add_mutually_exclusive_group()
    egroup.add_argument('--pure', action='store_true', help = \
                        'use a pure Python kernel instead of an IPython kernel')
    egroup.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
                       const='auto', help = \
        "Pre-load matplotlib and numpy for interactive use. If GUI is not \
         given, the GUI backend is matplotlib's, otherwise use one of: \
         ['tk', 'gtk', 'qt', 'wx', 'inline']."                                              )

    wgroup = parser.add_argument_group('widget options')
    wgroup.add_argument('--paging',
                        type=str,
                        default='inside',
                        choices=['inside', 'hsplit', 'vsplit', 'none'],
                        help='set the paging style [default inside]')
    wgroup.add_argument('--rich',
                        action='store_true',
                        help='enable rich text support')
    wgroup.add_argument('--gui-completion',
                        action='store_true',
                        help='use a GUI widget for tab completion')

    args = parser.parse_args()

    # Don't let Qt or ZMQ swallow KeyboardInterupts.
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # Create a KernelManager and start a kernel.
    kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq),
                                     sub_address=(args.ip, args.sub),
                                     rep_address=(args.ip, args.rep),
                                     hb_address=(args.ip, args.hb))
    if args.ip == LOCALHOST and not args.existing:
        if args.pure:
            kernel_manager.start_kernel(ipython=False)
        elif args.pylab:
            kernel_manager.start_kernel(pylab=args.pylab)
        else:
            kernel_manager.start_kernel()
    kernel_manager.start_channels()

    # Create the widget.
    app = QtGui.QApplication([])
    if args.pure:
        kind = 'rich' if args.rich else 'plain'
        widget = FrontendWidget(kind=kind, paging=args.paging)
    elif args.rich or args.pylab:
        widget = RichIPythonWidget(paging=args.paging)
    else:
        widget = IPythonWidget(paging=args.paging)
    widget.gui_completion = args.gui_completion
    widget.kernel_manager = kernel_manager

    # Create the main window.
    window = MainWindow(app, widget, args.existing)
    window.setWindowTitle('Python' if args.pure else 'IPython')
    window.show()

    # Start the application main loop.
    app.exec_()
Exemple #17
0
 def __init__(self, *args, **kw):
     RichIPythonWidget.__init__(self, *args, **kw)
     self._existing = True
     self._may_close = False
     self._confirm_exit = False
Exemple #18
0
 def __new__(cls, parent):
   return RichIPythonWidget.__new__(cls)
Exemple #19
0
def main():
    """ Entry point for application.
    """
    # Parse command line arguments.
    parser = ArgumentParser()
    kgroup = parser.add_argument_group('kernel options')
    kgroup.add_argument('-e', '--existing', action='store_true',
                        help='connect to an existing kernel')
    kgroup.add_argument('--ip', type=str, default=LOCALHOST,
                        help=\
            "set the kernel\'s IP address [default localhost].\
            If the IP address is something other than localhost, then \
            Consoles on other machines will be able to connect\
            to the Kernel, so be careful!")
    kgroup.add_argument('--xreq', type=int, metavar='PORT', default=0,
                        help='set the XREQ channel port [default random]')
    kgroup.add_argument('--sub', type=int, metavar='PORT', default=0,
                        help='set the SUB channel port [default random]')
    kgroup.add_argument('--rep', type=int, metavar='PORT', default=0,
                        help='set the REP channel port [default random]')
    kgroup.add_argument('--hb', type=int, metavar='PORT', default=0,
                        help='set the heartbeat port [default random]')

    egroup = kgroup.add_mutually_exclusive_group()
    egroup.add_argument('--pure', action='store_true', help = \
                        'use a pure Python kernel instead of an IPython kernel')
    egroup.add_argument('--pylab', type=str, metavar='GUI', nargs='?', 
                       const='auto', help = \
        "Pre-load matplotlib and numpy for interactive use. If GUI is not \
         given, the GUI backend is matplotlib's, otherwise use one of: \
         ['tk', 'gtk', 'qt', 'wx', 'inline'].")

    wgroup = parser.add_argument_group('widget options')
    wgroup.add_argument('--paging', type=str, default='inside',
                        choices = ['inside', 'hsplit', 'vsplit', 'none'],
                        help='set the paging style [default inside]')
    wgroup.add_argument('--plain', action='store_true',
                        help='disable rich text support')
    wgroup.add_argument('--gui-completion', action='store_true',
                        help='use a GUI widget for tab completion')
    wgroup.add_argument('--style', type=str,
                        choices = list(get_all_styles()),
                        help='specify a pygments style for by name')
    wgroup.add_argument('--stylesheet', type=str,
                        help='path to a custom CSS stylesheet')
    wgroup.add_argument('--colors', type=str, help = \
        "Set the color scheme (LightBG,Linux,NoColor). This is guessed \
         based on the pygments style if not set.")

    args = parser.parse_args()

    # parse the colors arg down to current known labels
    if args.colors:
        colors=args.colors.lower()
        if colors in ('lightbg', 'light'):
            colors='lightbg'
        elif colors in ('dark', 'linux'):
            colors='linux'
        else:
            colors='nocolor'
    elif args.style:
        if args.style=='bw':
            colors='nocolor'
        elif styles.dark_style(args.style):
            colors='linux'
        else:
            colors='lightbg'
    else:
        colors=None

    # Don't let Qt or ZMQ swallow KeyboardInterupts.
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # Create a KernelManager and start a kernel.
    kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq),
                                     sub_address=(args.ip, args.sub),
                                     rep_address=(args.ip, args.rep),
                                     hb_address=(args.ip, args.hb))
    if not args.existing:
        # if not args.ip in LOCAL_IPS+ALL_ALIAS:
        #     raise ValueError("Must bind a local ip, such as: %s"%LOCAL_IPS)

        kwargs = dict(ip=args.ip)
        if args.pure:
            kwargs['ipython']=False
        else:
            kwargs['colors']=colors
            if args.pylab:
                kwargs['pylab']=args.pylab

        kernel_manager.start_kernel(**kwargs)
    kernel_manager.start_channels()

    # Create the widget.
    app = QtGui.QApplication([])
    local_kernel = (not args.existing) or args.ip in LOCAL_IPS
    if args.pure:
        kind = 'plain' if args.plain else 'rich'
        widget = FrontendWidget(kind=kind, paging=args.paging, 
                                local_kernel=local_kernel)
    elif args.plain:
        widget = IPythonWidget(paging=args.paging, local_kernel=local_kernel)
    else:
        widget = RichIPythonWidget(paging=args.paging, 
                                   local_kernel=local_kernel)
    widget.gui_completion = args.gui_completion
    widget.kernel_manager = kernel_manager

    # Configure the style.
    if not args.pure: # only IPythonWidget supports styles
        if args.style:
            widget.syntax_style = args.style
            widget.style_sheet = styles.sheet_from_template(args.style, colors)
            widget._syntax_style_changed()
            widget._style_sheet_changed()
        elif colors:
            # use a default style
            widget.set_default_style(colors=colors)
        else:
            # this is redundant for now, but allows the widget's
            # defaults to change
            widget.set_default_style()

        if args.stylesheet:
            # we got an expicit stylesheet
            if os.path.isfile(args.stylesheet):
                with open(args.stylesheet) as f:
                    sheet = f.read()
                widget.style_sheet = sheet
                widget._style_sheet_changed()
            else:
                raise IOError("Stylesheet %r not found."%args.stylesheet)

    # Create the main window.
    window = MainWindow(app, widget, args.existing, may_close=local_kernel)
    window.setWindowTitle('Python' if args.pure else 'IPython')
    window.show()

    # Start the application main loop.
    app.exec_()