Ejemplo n.º 1
0
 def ipython_ui(self):
     from IPython.terminal.ipapp import TerminalIPythonApp
     import automate
     self.system.namespace.allow_overwrite.extend(['_', '__', '___', '_i', '_ii', '_iii', 'quit'])
     self.system.namespace.update({k: v for k, v in list(automate.__dict__.items()) if k not in self.system.namespace})
     term = TerminalIPythonApp(user_ns=self.system.namespace)
     self.system.namespace['term'] = term
     term.initialize([])
     term.start()
Ejemplo n.º 2
0
def load_config_for_embed_ipython(profile_name='debug'):
    """Load the a config file from the default ipython_dir.
    """
    ipython_dir = get_ipython_dir()
    profile_dir = os.path.join(ipython_dir, f'profile_{profile_name}')
    app = TerminalIPythonApp()
    app.config_file_paths.append(profile_dir)
    app.load_config_file()
    config = app.config
    # XXX: setting the profile in config seems to have no effect for InteractiveShellEmbed.
    # TODO: learn more about IPython internals...
    # fix history location with a little workaround
    if 'hist_file' not in config.HistoryAccessor:
        config.HistoryManager.hist_file = os.path.join(profile_dir, 'history.sqlite')
    return config
Ejemplo n.º 3
0
    def debug(self, err):
        import IPython
        ec, ev, tb = err
        # This is to work around issue #16, that occured when the exception
        # value was being passed as a string.
        if isinstance(ev, str):
            ev = ec(ev)
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        sys.stderr.write('\n- TRACEBACK --------------------------------------------------------------------\n')
        traceback.print_exception(ec, ev, tb)
        sys.stderr.write('--------------------------------------------------------------------------------\n')
        try:
            from IPython.terminal.ipapp import TerminalIPythonApp
            app = TerminalIPythonApp.instance()
            app.initialize(argv=['--no-banner'])
            try:
                # ipython >= 5.0
                p = IPython.terminal.debugger.TerminalPdb(app.shell.colors)
            except AttributeError:
                p = IPython.core.debugger.Pdb(app.shell.colors)

            p.reset()

            # inspect.getinnerframes() returns a list of frames information
            # from this frame to the one that raised the exception being
            # treated
            frame, filename, line, func_name, ctx, idx = inspect.getinnerframes(tb)[-1]
            p.interaction(frame, tb)
        finally:
            sys.stdout = stdout
Ejemplo n.º 4
0
def start(user_ns=None):
    # Make sure the log level is changed to warning
    CodecFactory()
    taurus.setLogLevel(taurus.Warning)

    try:
        check_requirements()
    except exception.SpockMissingRequirement as requirement:
        print(str(requirement))
        sys.exit(-1)
    except exception.SpockMissingRecommended as recommended:
        print(str(recommended))

    user_ns = user_ns or {}
    try:
        user_ns.update(get_args(sys.argv))
    except exception.SpockException as e:
        print(e)
        print('Starting normal IPython console')
    except KeyboardInterrupt:
        print("\nUser pressed Ctrl+C. Exiting...")
        sys.exit()
    except Exception as e:
        print('spock exited with an unmanaged exception: %s' % str(e))
        sys.exit(-2)

    app = TerminalIPythonApp.instance()
    app.initialize()
    #config = get_config()
    return app
Ejemplo n.º 5
0
Archivo: run.py Proyecto: shoptime/trex
def shell():
    """Start an interactive iPython shell"""

    from IPython.terminal.ipapp import TerminalIPythonApp
    import app.model as m
    from trex.support import quantum

    context = dict(
        app     = app,
        quantum = quantum,
        m       = m,
    )

    rc_file = os.path.normpath(os.path.join(app.root_path, os.pardir, 'shell.rc'))
    if os.access(rc_file, os.R_OK):
        execfile(rc_file, context, dict(context=context))

    shell = TerminalIPythonApp.instance(
        display_banner = False,
        quick          = True,
        user_ns        = context,
    )
    shell.initialize(argv=[])
    shell.shell.confirm_exit = False

    context = app.test_request_context('__shell__')
    context.push()
    shell.start()
    context.pop()
Ejemplo n.º 6
0
def shell():
    """Start an interactive iPython shell"""

    from IPython.terminal.ipapp import TerminalIPythonApp
    import app.model as m
    from trex.support import quantum

    context = dict(
        app     = app,
        quantum = quantum,
        m       = m,
    )

    rc_file = os.path.normpath(os.path.join(app.root_path, os.pardir, 'shell.rc'))
    if os.access(rc_file, os.R_OK):
        execfile(rc_file, context, dict(context=context))

    shell = TerminalIPythonApp.instance(
        display_banner = False,
        quick          = True,
        user_ns        = context,
    )
    shell.initialize(argv=[])
    shell.shell.confirm_exit = False

    def pretty_print(self, arg):
        from pprint import pformat
        import mongoengine
        import texttable

        output = None
        for line in self.shell.history_manager.get_tail(50):
            try:
                output = self.shell.history_manager.output_hist[line[1]]
            except KeyError:
                pass

        if isinstance(output, mongoengine.QuerySet):
            table = texttable.Texttable(max_width=0)
            table.set_deco(texttable.Texttable.HEADER)
            fields = output[0]._fields.keys()
            table.add_row(fields)
            for obj in output:
                table.add_row([str(getattr(obj, field)) for field in fields])
            pretty_output = table.draw()
        elif isinstance(output, mongoengine.Document) or isinstance(output, mongoengine.EmbeddedDocument):
            pretty_output = pformat(output.to_mongo().to_dict())
        else:
            pretty_output = pformat(output)

        print pretty_output

        return None

    shell.shell.define_magic('pp', pretty_print)

    context = app.test_request_context('__shell__')
    context.push()
    shell.start()
    context.pop()
Ejemplo n.º 7
0
    def run_shell(self, no_ipython, no_bpython, quiet):
        # based on the flask-script Shell.run() method
        context = self.get_context()

        if not no_bpython:
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not no_ipython:
            try:
                from IPython.terminal.ipapp import TerminalIPythonApp
                ipython_app = TerminalIPythonApp.instance(user_ns=context, display_banner=not quiet)
                ipython_app.initialize(argv=[])
                ipython_app.shell.show_banner(self.banner)
                ipython_app.start()
                return
            except ImportError:
                pass

        # Use basic python shell
        import code
        code.interact(self.banner, local=context)
def shell_cmd(verbose, with_req_context):
    try:
        from IPython.terminal.ipapp import TerminalIPythonApp
    except ImportError:
        click.echo(
            cformat(
                '%{red!}You need to `pip install ipython` to use the SNMS shell'
            ))
        sys.exit(1)

    current_app.config['REPL'] = True  # disables e.g. memoize_request
    request_stats_request_started()
    context, info = _make_shell_context()
    banner = cformat('%{yellow!}SNMS v{} is ready for your commands').format(
        snms.__version__)
    if verbose:
        banner = '\n'.join(info + ['', banner])
    ctx = current_app.make_shell_context()
    ctx.update(context)
    # clearCache()
    stack = ExitStack()
    if with_req_context:
        stack.enter_context(
            current_app.test_request_context(base_url=config.BASE_URL))
    with stack:
        ipython_app = TerminalIPythonApp.instance(user_ns=ctx,
                                                  display_banner=False)
        ipython_app.initialize(argv=[])
        ipython_app.shell.show_banner(banner)
        ipython_app.start()
Ejemplo n.º 9
0
    def __init__(self):
        """Constructor.

        Imports IPython's embedded shell with separator lines removed."""
        Shell.__init__(self)
        ConsoleProgressBarMixin.__init__(self)

        # We cannot use IPShellEmbed here because generator expressions do not
        # work there (e.g., set(g.degree(x) for x in [1,2,3])) where g comes
        # from an external context
        import sys

        from IPython import __version__ as ipython_version
        self.ipython_version = ipython_version

        try:
            # IPython >= 0.11 supports this
            try:
                from IPython.terminal.ipapp import TerminalIPythonApp
            except ImportError:
                from IPython.frontend.terminal.ipapp import TerminalIPythonApp
            self._shell = TerminalIPythonApp.instance()
            sys.argv.append("--nosep")
        except ImportError:
            # IPython 0.10 and earlier
            import IPython.Shell
            self._shell = IPython.Shell.start()
            self._shell.IP.runsource("from igraph import *")
            sys.argv.append("-nosep")
Ejemplo n.º 10
0
    def __init__(self):
        """Constructor.

        Imports IPython's embedded shell with separator lines removed."""
        Shell.__init__(self)
        ConsoleProgressBarMixin.__init__(self)

        # We cannot use IPShellEmbed here because generator expressions do not
        # work there (e.g., set(g.degree(x) for x in [1,2,3])) where g comes
        # from an external context
        import sys

        from IPython import __version__ as ipython_version
        self.ipython_version = ipython_version

        try:
            # IPython >= 0.11 supports this
            try:
                from IPython.terminal.ipapp import TerminalIPythonApp
            except ImportError:
                from IPython.frontend.terminal.ipapp import TerminalIPythonApp
            self._shell = TerminalIPythonApp.instance()
            sys.argv.append("--nosep")
        except ImportError:
            # IPython 0.10 and earlier
            import IPython.Shell
            self._shell = IPython.Shell.start()
            self._shell.IP.runsource("from igraph import *")
            sys.argv.append("-nosep")
Ejemplo n.º 11
0
def shell():
    """IPython shell"""
    from IPython.terminal.ipapp import TerminalIPythonApp
    app = TerminalIPythonApp.instance()
    app.user_ns = _make_shell_context()
    app.display_banner = False
    app.initialize(argv=[])
    app.start()
Ejemplo n.º 12
0
def run_python_interpreter(local_dict):
    from IPython import start_ipython as start
    from IPython.terminal.ipapp import TerminalIPythonApp

    mainModule = sys.modules["__main__"]
    start(user_ns=local_dict)
    sys.modules["__main__"] = mainModule

    TerminalIPythonApp.instance().display_banner = False

    return

    # Pass in the dictionary, for continuity from one session to the next.
    setquit()
    try:
        fd = sys.stdin.fileno()
        interacted = False
        if get_terminal_size(fd)[1] == 0:
            try:
                import termios

                old = termios.tcgetattr(fd)
                if old[3] & termios.ECHO:
                    # Need to turn off echoing and restore
                    new = termios.tcgetattr(fd)
                    new[3] = new[3] & ~termios.ECHO
                    try:
                        termios.tcsetattr(fd, termios.TCSADRAIN, new)
                        interacted = True
                        code.interact(
                            banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()'.",
                            readfunc=readfunc_stdio,
                            local=local_dict,
                        )
                    finally:
                        termios.tcsetattr(fd, termios.TCSADRAIN, old)
            except:
                pass
            # Don't need to turn off echoing
            if not interacted:
                code.interact(
                    banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.",
                    readfunc=readfunc_stdio,
                    local=local_dict,
                )
        else:
            # We have a real interactive terminal
            code.interact(
                banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.", local=local_dict
            )
    except SystemExit as e:
        global g_builtin_override_called
        if not g_builtin_override_called:
            print("Script exited with %s" % (e))
Ejemplo n.º 13
0
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
    ipshell = None
    try:
        import IPython
        have_ipython = True
    except ImportError:
        have_ipython = False
    if not ipshell and traceback and have_ipython:
        try:
            from IPython.core.debugger import Pdb
            from IPython.terminal.debugger import TerminalPdb
            from IPython.terminal.ipapp import TerminalIPythonApp
            ipapp = TerminalIPythonApp.instance()
            ipapp.interact = False  # Avoid output (banner, prints)
            ipapp.initialize(argv=[])
            def_colors = ipapp.shell.colors
            pdb_obj = TerminalPdb(def_colors)
            pdb_obj.botframe = None  # not sure. exception otherwise at quit
            ipshell = lambda: pdb_obj.interaction(None, traceback=traceback)
        except Exception:
            print("IPython Pdb exception:")
            better_exchook(*sys.exc_info(), autodebugshell=False)
    if not ipshell and have_ipython:
        try:
            import IPython
            import IPython.terminal.embed

            class DummyMod(object):
                pass

            module = DummyMod()
            module.__dict__ = user_global_ns
            module.__name__ = "_DummyMod"
            if "__name__" not in user_ns:
                user_ns = user_ns.copy()
                user_ns["__name__"] = "_DummyUserNsMod"
            ipshell = IPython.terminal.embed.InteractiveShellEmbed.instance(
                user_ns=user_ns, user_module=module)
        except Exception:
            print("IPython not available:")
            better_exchook(*sys.exc_info(), autodebugshell=False)
        else:
            if execWrapper:
                old = ipshell.run_code
                ipshell.run_code = lambda code: execWrapper(lambda: old(code))
    if ipshell:
        ipshell()
    else:
        print("Use simple debug shell:")
        if traceback:
            import pdb
            pdb.post_mortem(traceback)
        else:
            simple_debug_shell(user_global_ns, user_ns)
Ejemplo n.º 14
0
def launch_lambda_console(args, lib_dir=None, kernel_dir=None):
    install_kernelspec(lib_dir, kernel_dir)

    c = Config()
    # no idea why this doesn't work, but it doesn't...
    #c.IPythonConsoleApp.kernel_name="lambda-notebook"
    c.InteractiveShellApp.exec_lines=["import sys; sys.path.append(r\"%s\"); import lamb.lnsetup; lamb.lnsetup.ipython_setup()" % lib_dir]

    app = TerminalIPythonApp.instance(config=c)
    app.initialize(argv=args[1:])
    app.start()
Ejemplo n.º 15
0
def run_python_interpreter(local_dict):
    from IPython import start_ipython as start
    from IPython.terminal.ipapp import TerminalIPythonApp

    mainModule = sys.modules['__main__']
    start(user_ns=local_dict)
    sys.modules['__main__'] = mainModule

    TerminalIPythonApp.instance().display_banner = False

    return

    # Pass in the dictionary, for continuity from one session to the next.
    setquit()
    try:
        fd = sys.stdin.fileno()
        interacted = False
        if get_terminal_size(fd)[1] == 0:
            try:
                import termios
                old = termios.tcgetattr(fd)
                if old[3] & termios.ECHO:
                    # Need to turn off echoing and restore
                    new = termios.tcgetattr(fd)
                    new[3] = new[3] & ~termios.ECHO
                    try:
                        termios.tcsetattr(fd, termios.TCSADRAIN, new)
                        interacted = True
                        code.interact(
                            banner=
                            "Python Interactive Interpreter. To exit, type 'quit()', 'exit()'.",
                            readfunc=readfunc_stdio,
                            local=local_dict)
                    finally:
                        termios.tcsetattr(fd, termios.TCSADRAIN, old)
            except:
                pass
            # Don't need to turn off echoing
            if not interacted:
                code.interact(
                    banner=
                    "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.",
                    readfunc=readfunc_stdio,
                    local=local_dict)
        else:
            # We have a real interactive terminal
            code.interact(
                banner=
                "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.",
                local=local_dict)
    except SystemExit as e:
        global g_builtin_override_called
        if not g_builtin_override_called:
            print('Script exited with %s' % (e))
Ejemplo n.º 16
0
def debug_shell(app, parser):
    from IPython.terminal.ipapp import TerminalIPythonApp
    ip = TerminalIPythonApp.instance()
    ip.initialize(argv=[])
    ip.shell.user_global_ns['app'] = app
    ip.shell.user_global_ns['log'] = log
    ip.shell.user_global_ns['parser'] = parser
    def ipy_import(module_name, identifier):
        import importlib
        module = importlib.import_module(module_name)
        ip.shell.user_global_ns[identifier] = getattr(module, identifier) 
    ip.start()
Ejemplo n.º 17
0
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
    ipshell = None
    try:
        import IPython
        have_ipython = True
    except ImportError:
        have_ipython = False
    if not ipshell and traceback and have_ipython:
        try:
            from IPython.core.debugger import Pdb
            from IPython.terminal.debugger import TerminalPdb
            from IPython.terminal.ipapp import TerminalIPythonApp
            ipapp = TerminalIPythonApp.instance()
            ipapp.interact = False  # Avoid output (banner, prints)
            ipapp.initialize(argv=[])
            def_colors = ipapp.shell.colors
            pdb_obj = TerminalPdb(def_colors)
            pdb_obj.botframe = None  # not sure. exception otherwise at quit
            ipshell = lambda: pdb_obj.interaction(None, traceback=traceback)
        except Exception:
            print("IPython Pdb exception:")
            better_exchook(*sys.exc_info(), autodebugshell=False)
    if not ipshell and have_ipython:
        try:
            import IPython
            import IPython.terminal.embed
            class DummyMod(object): pass
            module = DummyMod()
            module.__dict__ = user_global_ns
            module.__name__ = "_DummyMod"
            if "__name__" not in user_ns:
                user_ns = user_ns.copy()
                user_ns["__name__"] = "_DummyUserNsMod"
            ipshell = IPython.terminal.embed.InteractiveShellEmbed.instance(
                user_ns=user_ns, user_module=module)
        except Exception:
            print("IPython not available:")
            better_exchook(*sys.exc_info(), autodebugshell=False)
        else:
            if execWrapper:
                old = ipshell.run_code
                ipshell.run_code = lambda code: execWrapper(lambda: old(code))
    if ipshell:
        ipshell()
    else:
        print("Use simple debug shell:")
        if traceback:
            import pdb
            pdb.post_mortem(traceback)
        else:
            simple_debug_shell(user_global_ns, user_ns)
Ejemplo n.º 18
0
def debug_shell(app, parser):
    from IPython.terminal.ipapp import TerminalIPythonApp
    ip = TerminalIPythonApp.instance()
    ip.initialize(argv=[])
    ip.shell.user_global_ns['app'] = app
    ip.shell.user_global_ns['log'] = log
    ip.shell.user_global_ns['parser'] = parser

    def ipy_import(module_name, identifier):
        import importlib
        module = importlib.import_module(module_name)
        ip.shell.user_global_ns[identifier] = getattr(module, identifier)

    ip.start()
Ejemplo n.º 19
0
def debug_shell(app):
    from IPython.terminal.ipapp import TerminalIPythonApp
    ip = TerminalIPythonApp.instance()
    ip.initialize(argv=[])
    ip.shell.user_global_ns['app'] = app
    ip.shell.user_global_ns['repo'] = app.repo
    ip.shell.user_global_ns['git'] = app.git
    ip.shell.user_global_ns['trac'] = app.trac
    def ipy_import(module_name, identifier):
        module = importlib.import_module(module_name)
        ip.shell.user_global_ns[identifier] = getattr(module, identifier) 
    ipy_import('git_trac.git_interface', 'GitInterface')
    ipy_import('git_trac.trac_server', 'TracServer')
    ip.start()
Ejemplo n.º 20
0
def launch_lambda_console(args, lib_dir=None, kernel_dir=None):
    install_kernelspec(lib_dir, kernel_dir)

    c = Config()
    # no idea why this doesn't work, but it doesn't...
    #c.IPythonConsoleApp.kernel_name="lambda-notebook"
    c.InteractiveShellApp.exec_lines = [
        "import sys; sys.path.insert(1,r\"%s\"); import lamb.lnsetup; lamb.lnsetup.ipython_setup()"
        % lib_dir
    ]

    app = TerminalIPythonApp.instance(config=c)
    app.initialize(argv=args[1:])
    app.start()
Ejemplo n.º 21
0
def _get_debugger_cls():
    shell = get_ipython()
    if shell is None:
        # Not inside IPython
        # Build a terminal app in order to force ipython to load the
        # configuration
        ipapp = TerminalIPythonApp()
        # Avoid output (banner, prints)
        ipapp.interact = False
        ipapp.initialize(["--no-term-title"])
        shell = ipapp.shell
    else:
        # Running inside IPython

        # Detect if embed shell or not and display a message
        if isinstance(shell, InteractiveShellEmbed):
            sys.stderr.write(
                "\nYou are currently into an embedded ipython shell,\n"
                "the configuration will not be loaded.\n\n")

    # Let IPython decide about which debugger class to use
    # This is especially important for tools that fiddle with stdout
    return shell.debugger_cls
Ejemplo n.º 22
0
def get_debugger():
    import IPython
    from IPython.terminal.ipapp import TerminalIPythonApp

    app = TerminalIPythonApp.instance()
    app.initialize(argv=['--no-banner'])
    try:
        # ipython >= 5.0
        p = IPython.terminal.debugger.TerminalPdb(app.shell.colors)
    except AttributeError:
        p = IPython.core.debugger.Pdb(app.shell.colors)

    p.reset()
    return p.interaction
Ejemplo n.º 23
0
def debug_shell(app):
    from IPython.terminal.ipapp import TerminalIPythonApp
    ip = TerminalIPythonApp.instance()
    ip.initialize(argv=[])
    ip.shell.user_global_ns['app'] = app
    ip.shell.user_global_ns['repo'] = app.repo
    ip.shell.user_global_ns['git'] = app.git
    ip.shell.user_global_ns['trac'] = app.trac
    def ipy_import(module_name, identifier):
        module = importlib.import_module(module_name)
        ip.shell.user_global_ns[identifier] = getattr(module, identifier) 
    ipy_import('git_trac.git_interface', 'GitInterface')
    ipy_import('git_trac.trac_server', 'TracServer')
    ip.start()
Ejemplo n.º 24
0
 def debug_shell(self, app):
     """
     Variant of :meth:`run_forever` that drops us into an IPython shell
     """
     from IPython.terminal.ipapp import TerminalIPythonApp
     ip = TerminalIPythonApp.instance()
     ip.initialize(argv=[])
     ip.shell.user_global_ns['app'] = app
     def ipy_import(module_name, identifier):
         module = importlib.import_module(module_name)
         ip.shell.user_global_ns[identifier] = getattr(module, identifier) 
     #ipy_import('sage_notebook.model.git_interface', 'GitInterface')
     from IPython.lib.inputhook import inputhook_manager
     inputhook_manager.set_inputhook(self.ipython_inputhook)
     ip.start()
Ejemplo n.º 25
0
    def debug(self, err):
        import IPython
        ec, ev, tb = err
        # This is to work around issue #16, that occured when the exception
        # value was being passed as a string.
        if isinstance(ev, str):
            ev = ec(ev)
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        sys.stderr.write(
            '\n- TRACEBACK --------------------------------------------------------------------\n'
        )
        traceback.print_exception(ec, ev, tb)
        sys.stderr.write(
            '--------------------------------------------------------------------------------\n'
        )
        try:
            try:
                # ipython >= 1.0
                from IPython.terminal.ipapp import TerminalIPythonApp
                app = TerminalIPythonApp.instance()
                app.initialize(argv=['--no-banner'])
                p = IPython.core.debugger.Pdb(app.shell.colors)
            except ImportError:
                try:
                    # 0.11 <= ipython <= 0.13
                    ip = IPython.core.ipapi.get()
                    p = IPython.core.debugger.Pdb(ip.colors)
                except AttributeError:
                    # ipython <= 0.10
                    shell = IPython.Shell.IPShell(argv=[''])
                    ip = IPython.ipapi.get()
                    p = IPython.Debugger.Pdb(ip.options.colors)

            p.reset()
            # inspect.getinnerframes() returns a list of frames information
            # from this frame to the one that raised the exception being
            # treated
            frame, filename, line, func_name, ctx, idx = inspect.getinnerframes(
                tb)[-1]
            p.interaction(frame, tb)
        finally:
            sys.stdout = stdout
Ejemplo n.º 26
0
 def ipython_ui(self):
     from IPython.terminal.ipapp import TerminalIPythonApp
     import automate
     self.system.namespace.allow_overwrite.extend(
         ['_', '__', '___', '_i', '_ii', '_iii', 'quit'])
     self.system.namespace.update({
         k: v
         for k, v in list(automate.__dict__.items())
         if k not in self.system.namespace
     })
     term = TerminalIPythonApp(user_ns=self.system.namespace)
     self.system.namespace['term'] = term
     term.initialize([])
     term.start()
Ejemplo n.º 27
0
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
    ipshell = None
    if traceback:
        try:
            from IPython.core.debugger import Pdb
            from IPython.terminal.ipapp import TerminalIPythonApp
            ipapp = TerminalIPythonApp.instance()
            ipapp.interact = False  # Avoid output (banner, prints)
            ipapp.initialize(argv=[])
            def_colors = ipapp.shell.colors
            pdb_obj = Pdb(def_colors)
            pdb_obj.botframe = None  # not sure. exception otherwise at quit
            ipshell = lambda: pdb_obj.interaction(None, traceback=traceback)
        except Exception:
            pass
    if not ipshell:
        try:
            import IPython
            import IPython.terminal.embed

            class DummyMod(object):
                pass

            module = DummyMod()
            module.__dict__ = user_global_ns
            module.__name__ = "DummyMod"
            ipshell = IPython.terminal.embed.InteractiveShellEmbed(
                user_ns=user_ns, user_module=module)
        except Exception:
            pass
        else:
            if execWrapper:
                old = ipshell.run_code
                ipshell.run_code = lambda code: execWrapper(lambda: old(code))
    if ipshell:
        ipshell()
    else:
        if traceback:
            import pdb
            pdb.post_mortem(traceback)
        else:
            simple_debug_shell(user_global_ns, user_ns)
Ejemplo n.º 28
0
def _launch_qt_console(ppid, connection_file):
    """called as a new process"""
    from IPython.terminal.ipapp import TerminalIPythonApp
    import threading
    import psutil
    import time
    
    # start a thread to kill this process when the parent process exits
    def thread_func():
        while True:
            if not psutil.pid_exists(ppid):
                os._exit(1)
            time.sleep(5)
    thread = threading.Thread(target=thread_func)
    thread.daemon = True
    thread.start()
    
    # start the qtconsole app
    app = TerminalIPythonApp.instance()
    app.initialize(["qtconsole", "--existing", connection_file])
    app.start()
Ejemplo n.º 29
0
    def run(self, pipe, no_ipython, no_bpython):
        if pipe:
            # User is attempting to pipe in script through stdin.
            text = sys.stdin.read()
            exec(text, None, _make_context())
            return

        # Try IPython (with autoreload)
        try:
            from IPython.terminal.ipapp import TerminalIPythonApp
            app = TerminalIPythonApp(user_ns=self.get_context())
            config_file = path.join(path.dirname(alchemist.__file__),
                                    "ipython_startup.ipy")
            app.init_shell()
            app.shell.banner = self.banner
            app.initialize(argv=["-i", config_file])
            app.start()
            return
        except ImportError:
            pass

        # Fallback to normal cycle.
        super(Shell, self).run(no_ipython=no_ipython, no_bpython=no_bpython)
Ejemplo n.º 30
0
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
    ipshell = None
    if traceback:
        try:
            from IPython.core.debugger import Pdb
            from IPython.terminal.ipapp import TerminalIPythonApp
            ipapp = TerminalIPythonApp.instance()
            ipapp.interact = False  # Avoid output (banner, prints)
            ipapp.initialize(argv=[])
            def_colors = ipapp.shell.colors
            pdb_obj = Pdb(def_colors)
            pdb_obj.botframe = None  # not sure. exception otherwise at quit
            ipshell = lambda: pdb_obj.interaction(None, traceback=traceback)
        except Exception:
            pass
    if not ipshell:
        try:
            import IPython
            import IPython.terminal.embed
            class DummyMod(object): pass
            module = DummyMod()
            module.__dict__ = user_global_ns
            module.__name__ = "DummyMod"
            ipshell = IPython.terminal.embed.InteractiveShellEmbed(
                user_ns=user_ns, user_module=module)
        except Exception:
            pass
        else:
            if execWrapper:
                old = ipshell.run_code
                ipshell.run_code = lambda code: execWrapper(lambda: old(code))
    if ipshell:
        ipshell()
    else:
        if traceback:
            import pdb
            pdb.post_mortem(traceback)
        else:
            simple_debug_shell(user_global_ns, user_ns)
Ejemplo n.º 31
0
def _launch_qt_console(ppid, connection_file):
    """called as a new process"""
    from IPython.terminal.ipapp import TerminalIPythonApp
    import threading
    import psutil
    import time

    # start a thread to kill this process when the parent process exits
    def thread_func():
        while True:
            if not psutil.pid_exists(ppid):
                os._exit(1)
            time.sleep(5)

    thread = threading.Thread(target=thread_func)
    thread.daemon = True
    thread.start()

    # start the qtconsole app
    app = TerminalIPythonApp.instance()
    app.initialize(["qtconsole", "--existing", connection_file])
    app.start()
Ejemplo n.º 32
0
def shell_cmd(verbose, with_req_context):
    try:
        from IPython.terminal.ipapp import TerminalIPythonApp
    except ImportError:
        click.echo(cformat('%{red!}You need to `pip install ipython` to use the Indico shell'))
        sys.exit(1)

    current_app.config['REPL'] = True  # disables e.g. memoize_request
    request_stats_request_started()
    context, info = _make_shell_context()
    banner = cformat('%{yellow!}Indico v{} is ready for your commands').format(indico.__version__)
    if verbose:
        banner = '\n'.join(info + ['', banner])
    ctx = current_app.make_shell_context()
    ctx.update(context)
    clearCache()
    stack = ExitStack()
    if with_req_context:
        stack.enter_context(current_app.test_request_context(base_url=config.BASE_URL))
    with stack:
        ipython_app = TerminalIPythonApp.instance(user_ns=ctx, display_banner=False)
        ipython_app.initialize(argv=[])
        ipython_app.shell.show_banner(banner)
        ipython_app.start()
Ejemplo n.º 33
0
    def run(self, pipe, no_ipython, no_bpython):
        if pipe:
            # User is attempting to pipe in script through stdin.
            text = sys.stdin.read()
            exec(text, None, _make_context())
            return

        # Try IPython (with autoreload)
        try:
            from IPython.terminal.ipapp import TerminalIPythonApp
            app = TerminalIPythonApp(user_ns=self.get_context())
            config_file = path.join(
                path.dirname(alchemist.__file__), "ipython_startup.ipy")
            app.init_shell()
            app.shell.banner = self.banner
            app.initialize(argv=["-i", config_file])
            app.start()
            return
        except ImportError:
            pass

        # Fallback to normal cycle.
        super(Shell, self).run(no_ipython=no_ipython, no_bpython=no_bpython)
Ejemplo n.º 34
0
        if dac_index < 0 or dac_index >= 6:
            raise ValueError("dac_index out of bounds")
        return self._write_reg(value, ADDR_DAC, dac_index)

    def interp_write(self, index, value, steps):
        if index < 0 or index >= 6:
            raise ValueError("dac_index out of bounds")
        self._write_reg(steps, ADDR_INTERP, index + 6)
        self._write_reg(value, ADDR_INTERP, index)

    def interp_read(self, index):
        if index < 0 or index >= 6:
            raise ValueError("dac_index out of bounds")
        steps = self._read_reg(ADDR_INTERP, index + 6)
        value = self._read_reg(ADDR_INTERP, index)
        return value, steps


if __name__ == "__main__":
    fpga = FPGA_USB_Interface()
    dct = {"fpga": fpga}

    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.display_banner = True
    app = TerminalIPythonApp()
    app.initialize(argv=[])
    app.shell.push(dct)
    app.shell.write("\nBuilt-in objects: %s\n" % str(dct))
    app.start()
    del app, fpga, dct
Ejemplo n.º 35
0
def ipython():
    from IPython.terminal.ipapp import TerminalIPythonApp
    app = TerminalIPythonApp.instance()
    app.initialize(argv=[])  # argv=[] instructs IPython to ignore sys.argv
    app.start()
Ejemplo n.º 36
0
from contextlib import contextmanager

__version__= "0.10.3"

from IPython import get_ipython
from IPython.core.debugger import BdbQuit_excepthook
from IPython.terminal.ipapp import TerminalIPythonApp
from IPython.terminal.embed import InteractiveShellEmbed


shell = get_ipython()
if shell is None:
    # Not inside IPython
    # Build a terminal app in order to force ipython to load the
    # configuration
    ipapp = TerminalIPythonApp()
    # Avoid output (banner, prints)
    ipapp.interact = False
    ipapp.initialize([])
    shell = ipapp.shell
else:
    # Running inside IPython

    # Detect if embed shell or not and display a message
    if isinstance(shell, InteractiveShellEmbed):
        sys.stderr.write(
            "\nYou are currently into an embedded ipython shell,\n"
            "the configuration will not be loaded.\n\n"
        )

# Let IPython decide about which debugger class to use
Ejemplo n.º 37
0
    trait_aliases = reverse_aliases(app)
    filename = options / (name + ".rst")

    text = [title, "=" * len(title), "\n"]
    if preamble is not None:
        text.append(preamble + "\n")

    text.append(app.document_config_options())

    text.extend(
        class_config_rst_doc(c, trait_aliases) for c in app._classes_inc_parents()
    )

    filename.write_text("\n".join(text))


if __name__ == "__main__":
    # Touch this file for the make target
    Path(generated).write_text("")

    write_doc("terminal", "Terminal IPython options", TerminalIPythonApp())
    write_doc(
        "kernel",
        "IPython kernel options",
        IPKernelApp(),
        preamble=(
            "These options can be used in :file:`ipython_kernel_config.py`. "
            "The kernel also respects any options in `ipython_config.py`"
        ),
    )
Ejemplo n.º 38
0
from contextlib import contextmanager

__version__ = "0.10.3"

from IPython import get_ipython
from IPython.core.debugger import BdbQuit_excepthook
from IPython.terminal.ipapp import TerminalIPythonApp
from IPython.terminal.embed import InteractiveShellEmbed

shell = get_ipython()
if shell is None:
    # Not inside IPython
    # Build a terminal app in order to force ipython to load the
    # configuration
    ipapp = TerminalIPythonApp()
    # Avoid output (banner, prints)
    ipapp.interact = False
    ipapp.initialize([])
    shell = ipapp.shell
else:
    # Running inside IPython

    # Detect if embed shell or not and display a message
    if isinstance(shell, InteractiveShellEmbed):
        sys.stderr.write(
            "\nYou are currently into an embedded ipython shell,\n"
            "the configuration will not be loaded.\n\n")

# Let IPython decide about which debugger class to use
# This is especially important for tools that fiddle with stdout
Ejemplo n.º 39
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        prog_name = argv[0]
        with_ipshell = False
        ignore_lock = False
        no_latex_output = True
        list_invoices = False
        output_file_name = "data.lco"
        invoice_number = None

        try:
            opts, args = getopt.getopt(argv[1:], "fhiln:po:", ["help"])
        except getopt.error as msg:
            raise Usage(msg)

        for opt in opts:
            if opt[0] in ["-f"]:
                print("ignoring lock")
                ignore_lock = True
            if opt[0] in ["-h", "--help"]:
                raise Usage("Help:")
            if opt[0] in ["-i"]:
                print("Using ipshell")
                with_ipshell = True
            if opt[0] in ["-l"]:
                print("listing all invoices")
                list_invoices = True
            if opt[0] in ["-n"]:
                invoice_number = int(opt[1])
                print("using invoice number", invoice_number)
                no_latex_output = False
            if opt[0] in ["-o"]:
                output_file_name = opt[1]
                print("using output file", output_file_name)
        if len(args) > 1:
            print("opts:", opts, "args:", args)
            raise Usage("Only one input can be accepted !")
        if len(args) == 0:
            raise Usage("No input given !")
        input_url = args[0]
    except Usage as err:
        if err.msg == "Help:":
            retcode = 0
        else:
            print("Error:", err.msg, file=sys.stderr)
            print("for help use --help", file=sys.stderr)
            retcode = 2

        print("Generate a LaTeX invoice or print out all invoices.")
        print()
        print("Usage:")
        print()
        print("Invoke with", prog_name, "input.")
        print("where input is")
        print("   filename")
        print("or file://filename")
        print("or mysql://user:password@host/databasename")
        print()
        print("-f             force open = ignore lock")
        print("-h or --help   for this help")
        print("-i             for ipython shell")
        print("-l             list all invoices")
        print(
            "-n number      use invoice number (no. from previous run with -l)"
        )
        print("-o name        use name as outputfile. default: data.lco")

        return retcode

    # Try to open the given input
    try:
        session = gnucash.Session(input_url, ignore_lock=ignore_lock)
    except Exception as exception:
        print("Problem opening input.")
        print(exception)
        return 2

    book = session.book
    root_account = book.get_root_account()
    comm_table = book.get_table()
    EUR = comm_table.lookup("CURRENCY", "EUR")

    invoice_list = get_all_invoices(book)

    if list_invoices:
        for number, invoice in enumerate(invoice_list):
            print(str(number) + ")")
            print(invoice)

    if not (no_latex_output):

        if invoice_number == None:
            print("Using the first invoice:")
            invoice_number = 0

        invoice = invoice_list[invoice_number]
        print("Using the following invoice:")
        print(invoice)

        lco_str = invoice_to_lco(invoice)

        # Opening output file
        f = open(output_file_name, "w")
        lco_str = lco_str.encode("latin1")
        f.write(lco_str)
        f.close()

    if with_ipshell:
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[])  # argv=[] instructs IPython to ignore sys.argv
        app.start()

    #session.save()
    session.end()
Ejemplo n.º 40
0
        f.write(('=' * len(title)) + '\n')
        f.write('\n')
        if preamble is not None:
            f.write(preamble + '\n\n')
        f.write(configdoc)
    with open('source/config/options/generated', 'a') as f:
        f.write(filename + '\n')


if __name__ == '__main__':
    # create empty file
    with open('source/config/options/generated', 'w'):
        pass

    write_doc('terminal', 'Terminal IPython options',
              TerminalIPythonApp().classes)
    write_doc(
        'kernel',
        'IPython kernel options',
        kernel_classes,
        preamble=
        "These options can be used in :file:`ipython_notebook_config.py` "
        "or in :file:`ipython_qtconsole_config.py`")
    nbclasses = set(NotebookApp().classes) - set(kernel_classes)
    write_doc('notebook',
              'IPython notebook options',
              nbclasses,
              preamble="Any of the :doc:`kernel` can also be used.")

    try:
        from IPython.qt.console.qtconsoleapp import IPythonQtConsoleApp
Ejemplo n.º 41
0
    if not (no_latex_output):

        if invoice_number == None:
            print "Using the first invoice:"
            invoice_number=0

        invoice=invoice_list[invoice_number]
        print "Using the following invoice:"
        print invoice

        lco_str=invoice_to_lco(invoice)

        # Opening output file
        f=open(output_file_name,"w")
        lco_str=lco_str.encode("latin1")
        f.write(lco_str)
        f.close()

    if with_ipshell:
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[]) # argv=[] instructs IPython to ignore sys.argv
        app.start()

    #session.save()
    session.end()

if __name__ == "__main__":
    sys.exit(main())

Ejemplo n.º 42
0
            raise ValueError("dac_index out of bounds")
        return self._write_reg(value, ADDR_DAC, dac_index)

    def interp_write(self, index, value, steps):
        if index < 0 or index >= 6:
            raise ValueError("dac_index out of bounds")
        self._write_reg(steps, ADDR_INTERP, index+6)
        self._write_reg(value, ADDR_INTERP, index)

    def interp_read(self, index):
        if index < 0 or index >= 6:
            raise ValueError("dac_index out of bounds")
        steps = self._read_reg(ADDR_INTERP, index+6)
        value = self._read_reg(ADDR_INTERP, index)
        return value, steps


if __name__ == "__main__":
    fpga = FPGA_USB_Interface()
    dct = {"fpga": fpga}

    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.display_banner = True
    app = TerminalIPythonApp()
    app.initialize(argv=[])
    app.shell.push(dct)
    app.shell.write("\nBuilt-in objects: %s\n" % str(dct))
    app.start()
    del app, fpga, dct

from IPython import get_ipython
from IPython.core.debugger import BdbQuit_excepthook
from IPython.terminal.ipapp import TerminalIPythonApp
from IPython.terminal.embed import InteractiveShellEmbed
try:
    import configparser
except:
    import ConfigParser as configparser

shell = get_ipython()
if shell is None:
    # Not inside IPython
    # Build a terminal app in order to force ipython to load the
    # configuration
    ipapp = TerminalIPythonApp()
    # Avoid output (banner, prints)
    ipapp.interact = False
    ipapp.initialize(['--no-term-title'])
    shell = ipapp.shell
else:
    # Running inside IPython

    # Detect if embed shell or not and display a message
    if isinstance(shell, InteractiveShellEmbed):
        sys.stderr.write(
            "\nYou are currently into an embedded ipython shell,\n"
            "the configuration will not be loaded.\n\n")

# Let IPython decide about which debugger class to use
# This is especially important for tools that fiddle with stdout
Ejemplo n.º 44
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        prog_name = argv[0]
        with_ipshell = False
        ignore_lock = False
        no_latex_output = True
        list_invoices = False
        output_file_name = "data.lco"
        invoice_number = None

        try:
            opts, args = getopt.getopt(argv[1:], "fhiln:po:", ["help"])
        except getopt.error as msg:
             raise Usage(msg)

        for opt in opts:
            if opt[0] in ["-f"]:
                print("ignoring lock")
                ignore_lock = True
            if opt[0] in ["-h","--help"]:
                raise Usage("Help:")
            if opt[0] in ["-i"]:
                print("Using ipshell")
                with_ipshell = True
            if opt[0] in ["-l"]:
                print("listing all invoices")
                list_invoices=True
            if opt[0] in ["-n"]:
                invoice_number = int(opt[1])
                print("using invoice number", invoice_number)
                no_latex_output = False
            if opt[0] in ["-o"]:
                output_file_name = opt[1]
                print("using output file", output_file_name)
        if len(args)>1:
            print("opts:",opts,"args:",args)
            raise Usage("Only one input can be accepted !")
        if len(args)==0:
            raise Usage("No input given !")
        input_url = args[0]
    except Usage as err:
        if err.msg == "Help:":
            retcode=0
        else:
            print("Error:", err.msg, file=sys.stderr)
            print("for help use --help", file=sys.stderr)
            retcode=2

        print("Generate a LaTeX invoice or print out all invoices.")
        print()
        print("Usage:")
        print()
        print("Invoke with",prog_name,"input.")
        print("where input is")
        print("   filename")
        print("or file://filename")
        print("or mysql://user:password@host/databasename")
        print()
        print("-f             force open = ignore lock")
        print("-h or --help   for this help")
        print("-i             for ipython shell")
        print("-l             list all invoices")
        print("-n number      use invoice number (no. from previous run with -l)")
        print("-o name        use name as outputfile. default: data.lco")

        return retcode

    # Try to open the given input
    try:
        session = gnucash.Session(input_url,ignore_lock=ignore_lock)
    except Exception as exception:
        print("Problem opening input.")
        print(exception)
        return 2

    book = session.book
    root_account = book.get_root_account()
    comm_table = book.get_table()
    EUR = comm_table.lookup("CURRENCY", "EUR")

    invoice_list=get_all_invoices(book)

    if list_invoices:
        for number,invoice in enumerate(invoice_list):
            print(str(number)+")")
            print(invoice)

    if not (no_latex_output):

        if invoice_number == None:
            print("Using the first invoice:")
            invoice_number=0

        invoice=invoice_list[invoice_number]
        print("Using the following invoice:")
        print(invoice)

        lco_str=invoice_to_lco(invoice)

        # Opening output file
        f=open(output_file_name,"w")
        lco_str=lco_str.encode("latin1")
        f.write(lco_str)
        f.close()

    if with_ipshell:
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[]) # argv=[] instructs IPython to ignore sys.argv
        app.start()

    #session.save()
    session.end()
Ejemplo n.º 45
0
here = abspath(dirname(__file__))
options = join(here, 'source', 'config', 'options')
generated = join(options, 'config-generated.txt')


def write_doc(name, title, app, preamble=None):
    filename = join(options, name + '.rst')
    with open(filename, 'w') as f:
        f.write(title + '\n')
        f.write(('=' * len(title)) + '\n')
        f.write('\n')
        if preamble is not None:
            f.write(preamble + '\n\n')
        f.write(app.document_config_options())


if __name__ == '__main__':
    # Touch this file for the make target
    with open(generated, 'w'):
        pass

    write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())
    write_doc(
        'kernel',
        'IPython kernel options',
        IPKernelApp(),
        preamble=(
            "These options can be used in :file:`ipython_kernel_config.py`. "
            "The kernel also respects any options in `ipython_config.py`"),
    )
Ejemplo n.º 46
0
        print str(recommended)

    user_ns = user_ns or {}
    try:
        user_ns.update(get_args(sys.argv))
    except exception.SpockException, e:
        print e.message
        print 'Starting normal IPython console'
    except KeyboardInterrupt:
        print "\nUser pressed Ctrl+C. Exiting..."
        sys.exit()
    except Exception, e:
        print 'spock exited with an unmanaged exception: %s' % str(e)
        sys.exit(-2)

    app = TerminalIPythonApp.instance()
    app.initialize()
    #config = get_config()
    return app


def mainloop(app=None, user_ns=None):
    if app is None:
        app = start(user_ns)
    app.start()


def prepare_input_handler():
    # initialize input handler as soon as possible
    import sardana.spock.inputhandler
    _ = sardana.spock.inputhandler.InputHandler()