Exemple #1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('cmd', nargs='*',
                        help='run this command and exit')
    args = parser.parse_args()

    c = Config()
    c.InteractiveShell.confirm_exit = False

    if args.cmd:
        c.PromptManager.out_template = ''
        c.HistoryAccessor.enabled = False

    ipshell = InteractiveShellEmbed(config=c, banner1='')
    ipshell.extension_manager.load_extension('xalc')

    if args.cmd:
        ipshell.run_cell(' '.join(args.cmd), store_history=False)
        sys.exit()

    print('xalc examples/tests:')
    for inp, out in tests:
        print(' {:10s} => {:10s}'.format(inp, out))

    ipshell()
Exemple #2
0
def make_shell(banner=u'IPython', **namespace):
    cfg = Config()
    prompt_config = cfg.PromptManager
    prompt_config.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
    prompt_config.out_template = r'<\#> '
    sh = InteractiveShellEmbed(config=cfg, banner1=banner)
    return sh.mainloop(local_ns=namespace)
def main(args):
    red = RedFlyingBaron.from_paths(args, verbose=True)
    shell = InteractiveShellEmbed(banner1="", banner2="")
    shell.push(["red", "RedFlyingBaron"])
    print "\nRedFlyingBaron instance is available under the name 'red':"
    print red
    shell.set_next_input("red")
    shell()
Exemple #4
0
def test_ipython(tmp_path):
    os.chdir(str(tmp_path))
    dotenv_file = tmp_path / '.env'
    dotenv_file.write_text("MYNEWVALUE=q1w2e3\n")
    ipshell = InteractiveShellEmbed()
    ipshell.magic("load_ext dotenv")
    ipshell.magic("dotenv")
    assert os.environ["MYNEWVALUE"] == 'q1w2e3'
Exemple #5
0
 def wrapper(namespace=namespace, banner=''):
     config = load_default_config()
     # Always use .instace() to ensure _instance propagation to all parents
     # this is needed for <TAB> completion works well for new imports
     # and clear the instance to always have the fresh env
     # on repeated breaks like with inspect_response()
     InteractiveShellEmbed.clear_instance()
     shell = InteractiveShellEmbed.instance(
         banner1=banner, user_ns=namespace, config=config)
     shell()
Exemple #6
0
def _ipython(local, banner):
    from IPython.terminal.embed import InteractiveShellEmbed
    from IPython.terminal.ipapp import load_default_config

    InteractiveShellEmbed.clear_instance()
    shell = InteractiveShellEmbed.instance(
        banner1=banner,
        user_ns=local,
        config=load_default_config()
    )
    shell()
Exemple #7
0
def console():
    """Starts an interactive IPython console"""

    import sys
    import builtins
    from IPython.terminal.embed import (load_default_config,
                                        InteractiveShell, InteractiveShellEmbed)

    header = 'Django debug console'
    config = load_default_config()
    config.InteractiveShellEmbed = config.TerminalInteractiveShell

    # save ps1/ps2 if defined
    ps1 = None
    ps2 = None
    try:
        ps1 = sys.ps1
        ps2 = sys.ps2
    except AttributeError:
        pass

    # save previous instance
    saved_shell_instance = InteractiveShell._instance
    if saved_shell_instance is not None:
        cls = type(saved_shell_instance)
        cls.clear_instance()

    # Starts shell
    retvalue = None

    def exit(value=None):
        nonlocal retvalue
        retvalue = value

    try:
        builtins.exit = exit
        shell = InteractiveShellEmbed.instance(config=config)
        shell(header=header, stack_depth=2, compile_flags=None)
        InteractiveShellEmbed.clear_instance()
    finally:
        pass

    # restore previous instance
    if saved_shell_instance is not None:
        cls = type(saved_shell_instance)
        cls.clear_instance()
        for subclass in cls._walk_mro():
            subclass._instance = saved_shell_instance
    if ps1 is not None:
        sys.ps1 = ps1
        sys.ps2 = ps2

    return retvalue
Exemple #8
0
 def ipython_console():
     """
     Run ipython console
     """
     from traitlets.config import Config
     from IPython.terminal.embed import InteractiveShellEmbed
     config = Config()
     # basic configuration
     config.TerminalInteractiveShell.confirm_exit = False
     #
     embed = InteractiveShellEmbed(config=config, banner1='')
     embed.mainloop()
Exemple #9
0
def ipython(message=None, frame=None):
    """Launch into customized IPython with greedy autocompletion and no prompt to exit.
       If stdin is not tty, just issue warning message."""
    import sys
    if os.isatty(sys.stdin.fileno()):
        config = Config({
            'InteractiveShell': {'confirm_exit': False, },
            'IPCompleter': {'greedy': True, }
        })
        InteractiveShellEmbed.instance(config=config)(message, local_ns=frame.f_locals, global_ns=frame.f_globals)
    else:
        warn("==========> IPython cannot be launched if stdin is not a tty.\n\n")
Exemple #10
0
def _interact(ns):
    shell = InteractiveShellEmbed(user_ns=ns)
    def _handle_exception(shell, exc_type, exc_value, exc_tb, tb_offset):
        exc_info = (exc_type, exc_value, exc_tb)
        shell.showtraceback(exc_info, tb_offset)
        if not _is_exception_in_ipython_eval(exc_tb):
            handle_exception(exc_info)
        if isinstance(exc_value, TerminatedException):
            context.result.add_error('Terminated')
            shell.exit_now = True

    shell.set_custom_exc((Exception, TerminatedException), _handle_exception)
    shell()
Exemple #11
0
def start_shell(controller=None):
    """Load Kytos interactive shell."""
    kytos_ascii = r"""
      _          _
     | |        | |
     | | ___   _| |_ ___  ___
     | |/ / | | | __/ _ \/ __|
     |   <| |_| | || (_) \__ \
     |_|\_\__,  |\__\___/|___/
            __/ |
           |___/
    """

    banner1 = f"""\033[95m{kytos_ascii}\033[0m
    Welcome to Kytos SDN Platform!

    We are making a huge effort to make sure that this console will work fine
    but for now it's still experimental.

    Kytos website.: https://kytos.io/
    Documentation.: https://docs.kytos.io/
    OF Address....:"""

    exit_msg = "Stopping Kytos daemon... Bye, see you!"

    if controller:
        address = controller.server.server_address[0]
        port = controller.server.server_address[1]
        banner1 += f" tcp://{address}:{port}\n"

        api_port = controller.api_server.port
        banner1 += f"    WEB UI........: http://{address}:{api_port}/\n"
        banner1 += f"    Kytos Version.: {__version__}"

    banner1 += "\n"

    cfg = Config()
    cfg.TerminalInteractiveShell.autocall = 2
    cfg.TerminalInteractiveShell.show_rewritten_input = False
    cfg.TerminalInteractiveShell.confirm_exit = False

    # Avoiding sqlite3.ProgrammingError when trying to save command history
    # on Kytos shutdown
    cfg.HistoryAccessor.enabled = False

    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1=banner1,
                                    exit_msg=exit_msg)
    ipshell.prompts = KytosPrompt(ipshell)

    ipshell()
Exemple #12
0
    def interact_ipython(header='', *args, **kwargs):
        global interact_ipython_

        def pre_prompt_hook(_):
            R.gInterpreter.EndOfLineAction()

        # Interact is a callable which starts an ipython shell
        if not interact_ipython_:
            interact_ipython_ = InteractiveShellEmbed(banner1=UP_LINE)
        # needed for graphics to work correctly
        interact_ipython_.set_hook('pre_prompt_hook', pre_prompt_hook)
        stack_depth = kwargs.pop("stack_depth", 0) + 2
        kwargs["stack_depth"] = stack_depth
        interact_ipython_(header, *args, **kwargs)
Exemple #13
0
def debughook(type, value, tb):
   if hasattr(sys, 'ps1') or not sys.stderr.isatty():
      # we are in interactive mode or we don't have a tty-like
      # device, so we call the default hook
      sys.__excepthook__(type, value, tb)
   else:
      # we are NOT in interactive mode, print the exception...
      #traceback.print_exception(type, value, tb)
      colorhook(type, value, tb)

      frame = tb.tb_next.tb_frame
      sh = InteractiveShellEmbed(
          banner1=termcolor.colored(
              "Custom Debug IPython Shell:\n", 'red'))
      sh.confirm_exit = False
      sh.mainloop(local_ns=frame.f_locals, global_ns=frame.f_globals)
Exemple #14
0
 def wrapper(namespace=namespace, banner=''):
     config = load_default_config()
     # Always use .instace() to ensure _instance propagation to all parents
     # this is needed for <TAB> completion works well for new imports
     shell = InteractiveShellEmbed.instance(
         banner1=banner, user_ns=namespace, config=config)
     shell()
Exemple #15
0
    def cmd_shell(self):
        # readline is used transparently by code.InteractiveConsole()
        import readline  # noqa: F401

        vars = {
            'concurrency_groups': self.config.concurrency_groups,
            'config': self.config,
            'datetime': datetime,
            'db': self.db,
            'dsari': dsari,
            'jobs': self.config.jobs,
        }
        banner = 'Additional variables available:\n'
        for (k, v) in vars.items():
            v = vars[k]
            if type(v) == dict:
                r = 'Dictionary ({} items)'.format(len(v))
            elif type(v) == list:
                r = 'List ({} items)'.format(len(v))
            else:
                r = repr(v)
            banner += '    {}: {}\n'.format(k, r)
        banner += '\n'

        sh = None
        try:
            from IPython.terminal.embed import InteractiveShellEmbed
            sh = InteractiveShellEmbed(user_ns=vars, banner2=banner)
            sh.excepthook = sys.__excepthook__
        except ImportError:
            print('ipython not available. Using normal python shell.')

        if sh:
            sh()
        else:
            import code

            class DsariConsole(code.InteractiveConsole):
                pass

            console_vars = vars.copy().update({
                '__name__': '__console__',
                '__doc__': None,
            })
            print(banner, end='')
            DsariConsole(locals=console_vars).interact()
Exemple #16
0
 def interact(self, **kwargs):
     from IPython.terminal.embed import InteractiveShellEmbed, load_default_config
     import sys
     config = kwargs.get('config')
     header = kwargs.pop('header', u'')
     compile_flags = kwargs.pop('compile_flags', None)
     if config is None:
         config = load_default_config()
         config.InteractiveShellEmbed = config.TerminalInteractiveShell
         kwargs['config'] = config
     frame = sys._getframe(1)
     shell = InteractiveShellEmbed.instance(
         _init_location_id='%s:%s' % (
             frame.f_code.co_filename, frame.f_lineno), **kwargs)
     shell(header=header, stack_depth=2, compile_flags=compile_flags,
           _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno))
     InteractiveShellEmbed.clear_instance()
Exemple #17
0
def ipy():
    """Run the IPython console in the context of the current frame.

    Useful for ad-hoc debugging."""
    from IPython.terminal.embed import InteractiveShellEmbed
    from IPython import embed
    frame = sys._getframe(1)
    with stdio_to_tty():
        shell = InteractiveShellEmbed.instance()
        shell(local_ns=frame.f_locals, global_ns=frame.f_globals)
Exemple #18
0
    def IPS():

        # let the user know, where this shell is 'waking up'
        # construct frame list
        # this will be printed in the header
        frame_info_list = []
        frame_list = []
        frame = inspect.currentframe()
        while not frame == None:
            frame_list.append(frame)
            info = inspect.getframeinfo(frame)
            frame_info_list.append(info)
            frame = frame.f_back

        frame_info_list.reverse()
        frame_list.reverse()
        frame_info_str_list = [format_frameinfo(fi) for fi in frame_info_list]

        custom_header1 = "----- frame list -----\n\n"
        frame_info_str = "\n--\n".join(frame_info_str_list[:-1])
        custom_header2 = "\n----- end of frame list -----\n"

        custom_header = "{0}{1}{2}".format(custom_header1, frame_info_str, custom_header2)

        # prevent IPython shell to be launched in IP-Notebook
        test_str = str(frame_info_list[0]) + str(frame_info_list[1])
        # print test_str
        if "IPython" in test_str and "zmq" in test_str:
            print "\n- Not entering IPython embedded shell  -\n"
            return

        # copied (and modified) from IPython/terminal/embed.py
        config = load_default_config()
        config.InteractiveShellEmbed = config.TerminalInteractiveShell

        # these two lines prevent problems in related to the initialization
        # of ultratb.FormattedTB below
        InteractiveShellEmbed.clear_instance()
        InteractiveShellEmbed._instance = None

        shell = InteractiveShellEmbed.instance()

        shell(header=custom_header, stack_depth=2)
Exemple #19
0
def attach():
    """
    Enter a python shell with contracts and blockchain client
    available.
    """
    project_dir = os.path.abspath(os.getcwd())
    contracts_meta = utils.load_contracts(project_dir)

    context = {
        'contracts': package_contracts(contracts_meta),
        'client': Client('127.0.0.1', '8545'),
    }

    contract_names = ', '.join(sorted(contracts_meta.keys()))

    banner = textwrap.dedent(
        """
        Python: {python_version}

        Populus: v{populus_version}

        Project Path: {project_dir}

        contracts  -> Contract classes
        client     -> Blockchain client ({client_type})

        Contracts: {contracts}
        """
    ).format(
        python_version=sys.version.partition('\n')[0],
        populus_version=populus.__version__,
        project_dir=project_dir,
        client_type="json-rpc",
        contracts=click.wrap_text(
            contract_names, initial_indent='', subsequent_indent=' ' * 4,
        ),
    ).strip()

    if is_ipython:
        shell = InteractiveConsole(user_ns=context)
    else:
        shell = InteractiveConsole(context)
    shell.interact(banner)
Exemple #20
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <IPython.core.interactiveshell.ExecutionResult object at 0x...>
    """
    try:
        cfg = copy.deepcopy(get_ipython().config)
    except NameError:
        cfg = copy.deepcopy(DEFAULT_SAGE_CONFIG)
    cfg.PromptManager['in_template'] = interface.name() + ': '
    cfg.PromptManager['in2_template'] = len(interface.name())*'.' + ': '

    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1='\n  --> Switching to %s <--\n\n'%interface,
                                    exit_msg = '\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Exemple #21
0
def ishell(local_ns):
    """Embed an IPython shell handing it the local namespace from
    :var:`local_ns`.
    """
    banner = (
        "Welcome to the pystuck interactive shell.\nUse the 'modules' dictionary "
        "to access remote modules (like 'os', or '__main__')\nUse the `%show "
        "threads` magic to display all thread stack traces.\n"
    )
    try:
        from IPython.terminal.embed import InteractiveShellEmbed

        ipshell = InteractiveShellEmbed(banner1=banner)
        ipshell.register_magics(IntrospectMagics)
        ipshell(local_ns=local_ns)
    except ImportError:
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        try:
            from IPython.Shell import IPShellEmbed

            ipshell = IPShellEmbed(argv=[], user_ns=local_ns, banner1=banner)
            ipshell.register_magics(IntrospectMagics)
            ipshell()
        except ImportError:
            # IPython not found at all, raise ImportError
            raise
Exemple #22
0
def embed2(**kwargs):
    """
    Modified from IPython.terminal.embed.embed so I can mess with stack_depth
    """
    config = kwargs.get('config')
    header = kwargs.pop('header', u'')
    stack_depth = kwargs.pop('stack_depth', 2)
    compile_flags = kwargs.pop('compile_flags', None)
    import IPython
    from IPython.core.interactiveshell import InteractiveShell
    from IPython.terminal.embed import InteractiveShellEmbed
    if config is None:
        config = IPython.terminal.ipapp.load_default_config()
        config.InteractiveShellEmbed = config.TerminalInteractiveShell
        kwargs['config'] = config
    #save ps1/ps2 if defined
    ps1 = None
    ps2 = None
    try:
        ps1 = sys.ps1
        ps2 = sys.ps2
    except AttributeError:
        pass
    #save previous instance
    saved_shell_instance = InteractiveShell._instance
    if saved_shell_instance is not None:
        cls = type(saved_shell_instance)
        cls.clear_instance()
    shell = InteractiveShellEmbed.instance(**kwargs)
    shell(header=header, stack_depth=stack_depth, compile_flags=compile_flags)
    InteractiveShellEmbed.clear_instance()
    #restore previous instance
    if saved_shell_instance is not None:
        cls = type(saved_shell_instance)
        cls.clear_instance()
        for subclass in cls._walk_mro():
            subclass._instance = saved_shell_instance
    if ps1 is not None:
        sys.ps1 = ps1
        sys.ps2 = ps2
Exemple #23
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <repr(<IPython.core.interactiveshell.ExecutionResult at 0x...>) failed: 
        AttributeError: type object 'ExecutionResult' has no attribute '__qualname__'>

    Note that the repr error is https://github.com/ipython/ipython/issues/9756
    """
    cfg = sage_ipython_config.copy()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1='\n  --> Switching to %s <--\n\n'%interface,
                                    exit_msg='\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface
    ipshell.prompts = InterfacePrompts(interface.name())

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Exemple #24
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <ExecutionResult object at ..., execution_count=None error_before_exec=None error_in_exec=None result=[ false, true, true, false, true, false, true, false, false, false ]>
    """
    cfg = sage_ipython_config.copy()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1='\n  --> Switching to %s <--\n\n'%interface,
                                    exit_msg='\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface
    ipshell.prompts = InterfacePrompts(interface.name())

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Exemple #25
0
    def raw_input(self, prompt1=''):
        prompt2 = console.AnsiConsole(StringIO.StringIO())
        prompt2.write("(")
        prompt2.pushColorCode(0xffa0a0)
        prompt2.write("warmice-batch")
        prompt2.popColorCode()
        prompt2.write(")")
        prompt = prompt1.replace('\n', "\n%s " % prompt2.getvalue())

        line = InteractiveShellEmbed.raw_input(self, prompt)
        if line == '':
            return self._last_line
        else:
            self._last_line = line
            return line
Exemple #26
0
def embed(pdb=False):
    from IPython.terminal.embed import InteractiveShellEmbed, load_default_config
    from IPython import Application, embed, get_ipython
    config = load_default_config()
    config.InteractiveShellEmbed = config.TerminalInteractiveShell
    config.InteractiveShellEmbed.pdb = pdb

    shell = InteractiveShellEmbed.instance(config=config)

    # my hook
    shell.set_hook('synchronize_with_editor', synchronize_with_editor)

    ### di, gu, gv etc...
    shell.safe_execfile('/home/ppalucki/workspace/djangoshellhelpers.py')

    ### start
    shell(stack_depth=2)
Exemple #27
0
def setup_shell():

    banner = '+-----------------------------------------------------------+\n'
    banner += ' APSG '
    banner += APSG_VERSION
    banner += ' [interactive shell] - http://ondrolexa.github.io/apsg\n'
    banner += '+-----------------------------------------------------------+\n'
    banner += '\n'
    banner += 'Commands: \n'
    banner += '\t"exit()" or press "Ctrl+ D" to exit the shell\n'
    banner += '\t"clear" to clear the shell screen\n'
    banner += '\n'
    banner += 'Documentation:\n'
    banner += '\thelp(Fol), ?Fol, Fol?, or Fol()? all do the same\n'
    banner += '\t"docs" will launch webbrowser showing documentation'
    banner += '\n'
    exit_msg = '\n... [Exiting the APSG interactive shell] ...\n'

    try:
        from traitlets.config import Config
        from IPython.terminal.embed import InteractiveShellEmbed

        cfg = Config()
        cfg.PromptManager.in_template = "APSG:\\#> "
        cfg.PromptManager.out_template = "APSG:\\#: "
        apsgShell = InteractiveShellEmbed(config=cfg, banner1=banner,
                                          exit_msg = exit_msg)
        apsgShell.define_magic("clear", magic_clear)
        #apsgShell.define_magic("docs", magic_docs)

    except ImportError:
        try:
            from IPython.Shell import IPShellEmbed
            argsv = ['-pi1','APSG:\\#>','-pi2','   .\\D.:','-po','APSG:\\#>','-nosep']

            apsgShell = IPShellEmbed(argsv)
            apsgShell.set_banner(banner)
            apsgShell.set_exit_msg(exit_msg)
            apsgShell.IP.api.expose_magic("clear", magic_clear)
        except ImportError:
            raise("ERROR: IPython shell failed to load")

    return apsgShell
Exemple #28
0
 def _embed_ipython(self, load_extension=None, kwargs=None):
     from IPython.terminal.ipapp import load_default_config
     from IPython.terminal.embed import InteractiveShellEmbed
     kwargs = kwargs or {}
     config = kwargs.get('config')
     header = kwargs.pop('header', u'')
     compile_flags = kwargs.pop('compile_flags', None)
     if config is None:
         config = load_default_config()
         config.InteractiveShellEmbed = config.TerminalInteractiveShell
         kwargs['config'] = config
     kwargs.setdefault('display_banner', False)
     self._ishell = InteractiveShellEmbed.instance(**kwargs)
     if load_extension:
         load_extension(self._ishell)
     # Stack depth is 3 because we use self.embed first
     self._ishell(header=header, stack_depth=3, compile_flags=compile_flags)
     return self._ishell
Exemple #29
0
    def initialize_variables_from_data(self, sess, n_batches_init=20):
        """Initialize variables smartly by looking at some training data."""

        tf.logging.info('Initializing variables from data')

        # setup data threads
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        tf.logging.info('data threads started')

        tf.logging.info('Initializing a from data')
        resp_expanded = tf.expand_dims(tf.expand_dims(self.resp, 1), 2)
        su_act_expanded = tf.expand_dims(self.probes.su_act, 3)
        a_avg = tf.expand_dims(
            tf.reduce_mean(tf.mul(su_act_expanded, resp_expanded), 0), 0)

        a_initialize = np.zeros(
            (1, self.params.dimx, self.params.dimy, self.params.n_cells))
        for ibatch in range(n_batches_init):
            print('init batch: %d' % ibatch)
            a_initialize += sess.run(a_avg)
        a_initialize /= n_batches_init

        a_max = np.max(np.reshape(a_initialize, [-1, self.params.n_cells]),
                       axis=0)
        mask = a_initialize > a_max * 0.7
        a_initial_masked = mask * np.log(a_max) - 40 * (1 - mask)
        a_initial_tf = tf.constant(a_initial_masked.astype(np.float32))

        a_init_tf = tf.assign(
            self.variables.a,
            tf.reshape(a_initial_tf, [-1, self.params.n_cells]))
        sess.run(a_init_tf)
        tf.logging.info('a initialized from data')

        from IPython.terminal.embed import InteractiveShellEmbed
        ipshell = InteractiveShellEmbed()
        ipshell()

        #coord.request_stop()
        #coord.join(threads)

        tf.logging.info('a initialzed based on average activity')
Exemple #30
0
def ipython(user_ns=None):
    return simple_repl(user_ns=user_ns)
    os.environ['IPYTHONDIR'] = ipydir
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
        from traitlets.config.loader import Config
        from IPython.terminal.prompts import Prompts, Token
    except ImportError:
        return simple_repl(user_ns=user_ns)

    class CustomPrompt(Prompts):
        def in_prompt_tokens(self, cli=None):
            return [
                (Token.Prompt, 'calibre['),
                (Token.PromptNum, get_version()),
                (Token.Prompt, ']> '),
            ]

        def out_prompt_tokens(self):
            return []

    defns = {'os': os, 're': re, 'sys': sys}
    defns.update(user_ns or {})

    c = Config()
    user_conf = os.path.expanduser(
        '~/.ipython/profile_default/ipython_config.py')
    if os.path.exists(user_conf):
        execfile(user_conf, {'get_config': lambda: c})
    c.TerminalInteractiveShell.prompts_class = CustomPrompt
    c.InteractiveShellApp.exec_lines = [
        'from __future__ import division, absolute_import, unicode_literals, print_function',
    ]
    c.TerminalInteractiveShell.confirm_exit = False
    c.TerminalInteractiveShell.banner1 = BANNER
    c.BaseIPythonApplication.ipython_dir = ipydir

    c.InteractiveShell.separate_in = ''
    c.InteractiveShell.separate_out = ''
    c.InteractiveShell.separate_out2 = ''

    ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns)
    ipshell()
Exemple #31
0
def ipython_shell(namespace=None, banner=None, debug=False):
    """Try to run IPython shell."""
    try:
        import IPython
    except ImportError:
        if debug:
            traceback.print_exc()
        print("IPython not available. Running default shell...")
        return
    # First try newer(IPython >=1.0) top `IPython` level import
    if hasattr(IPython, 'terminal'):
        from IPython.terminal.embed import InteractiveShellEmbed
        kwargs = dict(user_ns=namespace)
    else:
        from IPython.frontend.terminal.embed import InteractiveShellEmbed
        kwargs = dict(user_ns=namespace)
    if banner:
        kwargs = dict(banner1=banner)
    return InteractiveShellEmbed(**kwargs)
Exemple #32
0
def ipython(user_ns=None):
    os.environ['IPYTHONDIR'] = ipydir
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
        from traitlets.config.loader import Config
        from IPython.terminal.prompts import Prompts, Token
    except ImportError:
        return simple_repl(user_ns=user_ns)

    class CustomPrompt(Prompts):

        def in_prompt_tokens(self, cli=None):
            return [
                (Token.Prompt, 'calibre['),
                (Token.PromptNum, get_version()),
                (Token.Prompt, ']> '),
            ]

        def out_prompt_tokens(self):
            return []

    defns = {'os':os, 're':re, 'sys':sys}
    defns.update(user_ns or {})

    c = Config()
    user_conf = os.path.expanduser('~/.ipython/profile_default/ipython_config.py')
    if os.path.exists(user_conf):
        execfile(user_conf, {'get_config': lambda: c})
    c.TerminalInteractiveShell.prompts_class = CustomPrompt
    c.InteractiveShellApp.exec_lines = [
        'from __future__ import division, absolute_import, unicode_literals, print_function',
        ]
    c.TerminalInteractiveShell.confirm_exit = False
    c.TerminalInteractiveShell.banner1 = BANNER
    c.BaseIPythonApplication.ipython_dir = ipydir

    c.InteractiveShell.separate_in = ''
    c.InteractiveShell.separate_out = ''
    c.InteractiveShell.separate_out2 = ''

    ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns)
    ipshell()
Exemple #33
0
    def embed(self):
        if not config["preview"]:
            logger.warning(
                "Called embed() while no preview window is available.")
            return
        if config["write_to_movie"]:
            logger.warning("embed() is skipped while writing to a file.")
            return

        self.renderer.render(self, -1, self.moving_mobjects)

        # Configure IPython shell.
        from IPython.terminal.embed import InteractiveShellEmbed

        shell = InteractiveShellEmbed()

        # Have the frame update after each command
        shell.events.register(
            "post_run_cell",
            lambda *a, **kw: self.renderer.render(self, -1, self.
                                                  moving_mobjects),
        )

        # Use the locals of the caller as the local namespace
        # once embeded, and add a few custom shortcuts.
        local_ns = inspect.currentframe().f_back.f_locals
        # local_ns["touch"] = self.interact
        for method in (
                "play",
                "wait",
                "add",
                "remove",
                "interact",
                # "clear",
                # "save_state",
                # "restore",
        ):
            local_ns[method] = getattr(self, method)
        shell(local_ns=local_ns, stack_depth=2)

        # End scene when exiting an embed.
        raise Exception("Exiting scene.")
Exemple #34
0
def interactive_shell(bot, trigger):
    """
    Starts an interactive IPython console
    """
    global console
    if not trigger.admin:
        bot.say('Only admins can start the interactive console')
        return
    if 'iconsole_running' in bot.memory and bot.memory['iconsole_running']:
        bot.say('Console already running')
        return
    if not sys.__stdout__.isatty():
        bot.say('A tty is required to start the console')
        return
    if bot._daemon:
        bot.say('Can\'t start console when running as a daemon')
        return

    # Backup stderr/stdout wrappers
    old_stdout = sys.stdout
    old_stderr = sys.stderr

    # IPython wants actual stderr and stdout
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__

    banner1 = 'Sopel interactive shell (embedded IPython)'
    banner2 = '`bot` and `trigger` are available. To exit, type exit'
    exitmsg = 'Interactive shell closed'

    console = InteractiveShellEmbed(banner1=banner1,
                                    banner2=banner2,
                                    exit_msg=exitmsg)

    bot.memory['iconsole_running'] = True
    bot.say('console started')
    console()
    bot.memory['iconsole_running'] = False

    # Restore stderr/stdout wrappers
    sys.stdout = old_stdout
    sys.stderr = old_stderr
Exemple #35
0
def ipython(user_ns=None):
    ipydir = os.path.join(cache_dir, 'ipython')
    os.environ['IPYTHONDIR'] = ipydir
    BANNER = ('Welcome to the interactive vise shell!\n')
    from IPython.terminal.embed import InteractiveShellEmbed
    from IPython.terminal.prompts import Prompts, Token
    from traitlets.config.loader import Config

    class CustomPrompt(Prompts):
        def in_prompt_tokens(self, cli=None):
            return [
                (Token.Prompt, 'vise['),
                (Token.PromptNum, str_version),
                (Token.Prompt, ']> '),
            ]

        def out_prompt_tokens(self):
            return []

    defns = {'os': os, 're': re, 'sys': sys}
    defns.update(user_ns or {})

    c = Config()
    user_conf = os.path.expanduser(
        '~/.ipython/profile_default/ipython_config.py')
    if os.path.exists(user_conf):
        import runpy
        runpy.run_path(user_conf, {'get_config': lambda: c}, '__main__')
    c.TerminalInteractiveShell.prompts_class = CustomPrompt
    c.InteractiveShellApp.exec_lines = [
        'from __future__ import division, absolute_import, unicode_literals, print_function',
    ]
    c.TerminalInteractiveShell.confirm_exit = False
    c.TerminalInteractiveShell.banner1 = BANNER
    c.BaseIPythonApplication.ipython_dir = ipydir

    c.InteractiveShell.separate_in = ''
    c.InteractiveShell.separate_out = ''
    c.InteractiveShell.separate_out2 = ''

    ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns)
    ipshell()
Exemple #36
0
def interact(session=False, apk=None):
    """
    Start an interactive shell
    :param session:
    :param apk:
    :return:
    """
    if session:
        CONF["SESSION"] = Session(export_ipython=True)

    if apk:
        print("Loading apk {}...".format(os.path.basename(apk)))
        print("Please be patient, this might take a while.")
        # TODO we can export fancy aliases for those as well...
        a, d, dx = AnalyzeAPK(apk)

    cfg = Config()
    ipshell = InteractiveShellEmbed(config=cfg, banner1="{} started".format(_version_string))
    init_print_colors()
    ipshell()
Exemple #37
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('filenames', nargs='+')
    args = parser.parse_args()

    basenames = [os.path.splitext(os.path.basename(f))[0]
                 for f in args.filenames]
    files = [parse(f) for f in args.filenames]
    vars = dict(parse=parse)
    pages_str = []
    for filename, basename, f in zip(args.filenames, basenames, files):
        varname = basename.replace('-', '_')
        vars[varname] = f
        for i, p in enumerate(f.pages):
            pages_str.append('%s.pages[%r] == %r' % (varname, i, p))

    check_styles(files)

    ipshell = InteractiveShellEmbed(user_ns=vars)
    ipshell('\n'.join(pages_str))
Exemple #38
0
        def shell(ipython: bool = True):
            """Run the application shell.

            :param ipython: Use IPython as a shell
            """
            banner = f"Interactive Muffin {__version__} Shell"
            banner = f"\n{banner}\n{'-' * len(banner)}\nPython: {sys.version}\n\n"
            ctx = app.cfg.MANAGE_SHELL
            if callable(ctx):
                ctx = ctx()
            banner += f"Loaded globals: {list(ctx.keys())}\n"
            if ipython:
                try:
                    from IPython.terminal.embed import InteractiveShellEmbed
                    sh = InteractiveShellEmbed(banner1=banner, user_ns=ctx)
                    return sh()
                except ImportError:
                    pass

            code.interact(banner, local=ctx)
Exemple #39
0
def IPShell(argv=None, user_ns=None, banner=None):
    if argv is None:
        argv = []

    try:
        from IPython.terminal.embed import InteractiveShellEmbed
        from IPython.config.loader import Config

        cfg = Config()
        cfg.InteractiveShellEmbed.autocall = 2

        shell = InteractiveShellEmbed(config=cfg,
                                      user_ns=user_ns,
                                      banner2=unicode(banner))
        shell(local_ns=user_ns)
    except ImportError:
        from IPython import Shell

        # IPython < 0.11
        Shell.IPShell(argv=argv, user_ns=user_ns).mainloop(banner=banner)
Exemple #40
0
def shell(obj, shell):
    env = obj.pyramid_env
    env['app'] = obj.app

    values = {
        'app': 'The WSGI application',
        'registry': 'Active Pyramid registry',
        'request': 'Active request object',
    }
    banner = 'Environment:'

    for key in sorted(values.keys()):
        banner += '\n %-12s %s' % (key, values[key])

    if shell == 'ipython':
        from IPython.terminal.embed import InteractiveShellEmbed
        InteractiveShellEmbed(banner2=banner, user_ns=env)()
    elif shell == 'bpython':
        from bpython import embed
        embed(locals_=env, banner=banner)()
Exemple #41
0
    def _run_shell(self, base_module, locs, disable_ipython):
        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'WebTest.TestApp wrapped around wsgiapp')

        try:
            if disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                try:
                    # ipython >= 1.0
                    from IPython.terminal.embed import InteractiveShellEmbed
                except ImportError:
                    # ipython >= 0.11
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed.instance(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed()
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            shell(local_ns=locs)
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "TurboGears2 Interactive Shell\n%sython %s\n\n" % \
                        (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass

            shell.interact(banner)
Exemple #42
0
    def run(self):
        """ allows to run an ipython shell with the CLI's context vars """
        namespace = self.namespace
        try:
            from IPython.terminal.embed import InteractiveShellEmbed
            use_ipython = True
        except ImportError:
            use_ipython = False

        if use_ipython:
            shell = InteractiveShellEmbed(user_ns=namespace)
            shell()
        else:
            self.mini_shell(namespace=namespace)

        if self._quit_function:
            try:
                self._quit_function(self)
            except TypeError:
                logger.warning("using obsolete quit function without argument")
                self._quit_function()
Exemple #43
0
def main():
    args = sys.argv[1:]
    if args[0] == 'server':
        sys.argv = ['gunicorn']
        return WSGIApplication('%(prog)s [OPTIONS]').run()
    elif args[0] == 'shell':
        _app = create_app()
        banner = '[EMAIL Console]:\n`EMAIL_ENV` is {}\nplease be careful\nthe following vars are included:\n`app` (the current app)\n'.format(  # noqa
            os.environ.get('EMAIL_ENV', 'testing'))
        ctx = {'app': _app}
        from IPython.terminal.embed import InteractiveShellEmbed
        ipshell = InteractiveShellEmbed(user_ns=ctx, banner1=banner)
        ipshell()
        return 0
    elif args[0] == 'celery':
        create_app()
        from celery.__main__ import main as celerymain
        sys.argv = args
        sys.argv.extend(['-A', 'app.extensions:celeryapp'])
        return celerymain()
    raise KeyError
Exemple #44
0
def main():
    argv = sys.argv[1:]

    banner = "\nnetaddr shell %s - %s\n" % (netaddr.__version__, __doc__)
    exit_msg = "\nShare and enjoy!"
    rc_override = None

    try:
        try:
            # ipython >= 0.11
            from IPython.terminal.embed import InteractiveShellEmbed
            ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
        except ImportError:
            # ipython < 0.11
            from IPython.Shell import IPShellEmbed
            ipshell = IPShellEmbed(argv, banner, exit_msg, rc_override)
    except ImportError:
        sys.stderr.write('IPython (http://ipython.scipy.org/) not found!\n')
        sys.exit(1)

    ipshell()
Exemple #45
0
    def embed(self):
        if not self.preview:
            # If the scene is just being
            # written, ignore embed calls
            return
        self.stop_skipping()
        self.linger_after_completion = False
        self.update_frame()

        shell = InteractiveShellEmbed()
        # Have the frame update after each command
        shell.events.register('post_run_cell', lambda *a, **kw: self.update_frame())
        # Use the locals of the caller as the local namespace
        # once embeded, and add a few custom shortcuts
        local_ns = inspect.currentframe().f_back.f_locals
        local_ns["touch"] = self.interact
        for term in ("play", "wait", "add", "remove", "clear", "save_state", "restore"):
            local_ns[term] = getattr(self, term)
        shell(local_ns=local_ns, stack_depth=2)
        # End scene when exiting an embed.
        raise EndSceneEarlyException()
Exemple #46
0
def start_python_console(namespace=None, noipython=False, banner=''):
    """Start Python console bound to the given namespace. If IPython is
    available, an IPython console will be started instead, unless `noipython`
    is True. Also, tab completion will be used on Unix systems.
    """
    if namespace is None:
        namespace = {}

    try:
        try:  # use IPython if available
            if noipython:
                raise ImportError()

            try:
                from IPython.terminal.embed import InteractiveShellEmbed
                from IPython.terminal.ipapp import load_default_config
            except ImportError:
                from IPython.frontend.terminal.embed import InteractiveShellEmbed
                from IPython.frontend.terminal.ipapp import load_default_config

            config = load_default_config()
            shell = InteractiveShellEmbed(banner1=banner,
                                          user_ns=namespace,
                                          config=config)
            shell()
        except ImportError:
            import code

            try:  # readline module is only available on unix systems
                import readline
            except ImportError:
                pass
            else:
                pass
                # import rlcompleter

                readline.parse_and_bind("tab:complete")
            code.interact(banner=banner, local=namespace)
    except SystemExit:  # raised when using exit() in python code.interact
        pass
Exemple #47
0
def get_ipshell():
    from IPython import embed
    from IPython.terminal.embed import InteractiveShellEmbed
    from IPython.core.completer import Completer

    Completer.use_jedi = False

    banner = """
    Openshift Configuration Explorer

    Tutorial: https://github.com/RedHatInsights/insights-core/blob/master/docs/notebooks/Parsr%20Query%20Tutorial.ipynb

    conf is the top level configuration. Use conf.get_keys() to see first level
    keys.

    Available Predicates
        lt, le, eq, gt, ge

        isin, contains

        startswith, endswith

        ieq, icontains, istartswith, iendswith

    Available Operators
        ~ (not)
        | (or)
        & (and)

    Example
        api = conf.where("kind", "KubeAPIServer")
        latest = api.status.latestAvailableRevision.value
        api.status.nodeStatuses.where("currentRevision", ~eq(latest))
    """
    exit_msg = '\nExiting IPython'

    try:
        return InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
    except:
        return embed
Exemple #48
0
def _startipython(ui, repo):
    from IPython.terminal.embed import InteractiveShellEmbed
    from IPython.terminal.ipapp import load_default_config

    bannermsg = "loaded repo:  %s\n" "using source: %s" % (
        repo and repo.root or "(none)",
        mercurial.__path__[0],
    ) + ("\n\nAvailable variables:\n"
         " m:  edenscm.mercurial\n"
         " x:  edenscm.hgext\n"
         " b:  bindings\n"
         " ui: the ui object\n"
         " c:  run command and take output\n")
    if repo:
        bannermsg += (" repo: the repo object\n"
                      " serv: commitcloud service\n"
                      " api: edenapi client\n"
                      " cl: repo.changelog\n"
                      " mf: repo.manifestlog\n"
                      " ml: repo.svfs.metalog\n"
                      " ms: repo._mutationstore\n")
    bannermsg += """
Available IPython magics (auto magic is on, `%` is optional):
 time:   measure time
 timeit: benchmark
 trace:  run and print ASCII trace (better with --trace command flag)
 hg:     run commands inline
"""

    config = load_default_config()
    config.InteractiveShellEmbed = config.TerminalInteractiveShell
    config.InteractiveShell.automagic = True
    config.InteractiveShell.banner2 = bannermsg
    config.InteractiveShell.confirm_exit = False

    shell = InteractiveShellEmbed.instance(config=config)
    _configipython(ui, shell)

    locals().update(globals())
    shell()
Exemple #49
0
def launch_ipython_legacy_shell(args):  # pylint: disable=unused-argument
    """Open the SolveBio shell (IPython wrapper) for older IPython versions"""
    try:
        from IPython.config.loader import Config
    except ImportError:
        _print("The SolveBio Python shell requires IPython.\n"
               "To install, type: 'pip install ipython'")
        return False

    try:
        # see if we're already inside IPython
        get_ipython  # pylint: disable=undefined-variable
    except NameError:
        cfg = Config()
        prompt_config = cfg.PromptManager
        prompt_config.in_template = '[SolveBio] In <\\#>: '
        prompt_config.in2_template = '   .\\D.: '
        prompt_config.out_template = 'Out<\\#>: '
        banner1 = '\nSolveBio Python shell started.'

        exit_msg = 'Quitting SolveBio shell.'
    else:
        _print("Running nested copies of IPython.")
        cfg = Config()
        banner1 = exit_msg = ''

    # First import the embeddable shell class
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
    except ImportError:
        # pylint: disable=import-error,no-name-in-module
        from IPython.frontend.terminal.embed import InteractiveShellEmbed

    path = os.path.dirname(os.path.abspath(__file__))
    init_file = '{}/ipython_init.py'.format(path)
    exec(compile(open(init_file).read(), init_file, 'exec'), globals(),
         locals())

    InteractiveShellEmbed(config=cfg, banner1=banner1, exit_msg=exit_msg)()
Exemple #50
0
def interact(scope):
    banner = "gem5 Interactive Console"

    ipshell = None
    prompt_in1 = "gem5 \\#> "
    prompt_out = "gem5 \\#: "

    # Is IPython version 0.10 or earlier available?
    try:
        from IPython.Shell import IPShellEmbed
        ipshell = IPShellEmbed(
            argv=["-prompt_in1", prompt_in1, "-prompt_out", prompt_out],
            banner=banner,
            user_ns=scope)
    except ImportError:
        pass

    # Is IPython version 0.11 or later available?
    if not ipshell:
        try:
            import IPython
            from IPython.config.loader import Config
            from IPython.terminal.embed import InteractiveShellEmbed

            cfg = Config()
            cfg.PromptManager.in_template = prompt_in1
            cfg.PromptManager.out_template = prompt_out
            ipshell = InteractiveShellEmbed(config=cfg,
                                            user_ns=scope,
                                            banner1=banner)
        except ImportError:
            pass

    if ipshell:
        ipshell()
    else:
        # Use the Python shell in the standard library if IPython
        # isn't available.
        code.InteractiveConsole(scope).interact(banner)
Exemple #51
0
def cli():
    try:
        from IPython.terminal.prompts import Prompts, Token
        from IPython.terminal.embed import InteractiveShellEmbed
        from traitlets.config.loader import Config
        class CustomPrompt(Prompts):
            def in_prompt_tokens(self, cli=None):
               return [
                    (Token.Prompt, 'amoco>'),
                    ]
            def out_prompt_tokens(self):
               return [
                    (Token.OutPrompt, ''),
                ]
        cfg = Config()
        cfg.TerminalInteractiveShell.prompts_class=CustomPrompt
        ipshell = InteractiveShellEmbed(config=cfg)
        ipshell()

    except ImportError:
        from code import interact
        interact(local=dict(globals(), **locals()))
Exemple #52
0
        def shell(ipython: bool = True):
            """Run the application shell.

            :param ipython: Use IPython as shell
            """
            banner = '\nInteractive Muffin Shell\n'
            namespace = app.cfg.MANAGE_SHELL
            if callable(namespace):
                namespace = namespace()
            banner += "Loaded objects: %s" % list(namespace.keys())
            if ipython:
                try:
                    from IPython.terminal.embed import InteractiveShellEmbed
                    sh = InteractiveShellEmbed(banner1=banner)
                except ImportError:
                    pass
                else:
                    sh(local_ns=namespace)
                    return

            from code import interact
            interact(banner, local=namespace)
Exemple #53
0
def IPShell(argv=None, user_ns=None, banner=None):
    if argv is None:
        argv = []

    try:
        # pylint: disable=g-import-not-at-top
        from IPython.terminal.embed import InteractiveShellEmbed
        from IPython.config.loader import Config
        # pylint: enable=g-import-not-at-top

        cfg = Config()
        cfg.InteractiveShellEmbed.autocall = 2

        shell = InteractiveShellEmbed(config=cfg, user_ns=user_ns)
        shell(local_ns=user_ns)
    except ImportError:
        # pylint: disable=g-import-not-at-top
        from IPython import Shell
        # pylint: enable=g-import-not-at-top

        # IPython < 0.11
        Shell.IPShell(argv=argv, user_ns=user_ns).mainloop(banner=banner)
Exemple #54
0
def IPyBreak_base():
    '''A routine that invokes an IPython session at the calling location
    This routine is only used when debug=True is set in config.py
    '''
    savehook = sys.excepthook  # save the exception hook
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
    except ImportError:
        try:
            # try the IPython 0.12 approach
            from IPython.frontend.terminal.embed import InteractiveShellEmbed
        except ImportError:
            print 'IPython InteractiveShellEmbed not found'
            return
    import inspect
    ipshell = InteractiveShellEmbed()

    frame = inspect.currentframe().f_back
    msg = 'Entering IPython console inside {0.f_code.co_filename} at line {0.f_lineno}'.format(
        frame)
    ipshell(msg, stack_depth=2)  # Go up one level, to see the calling routine
    sys.excepthook = savehook  # reset IPython's change to the exception hook
Exemple #55
0
def drop_to_ipython(local_variables, *variables_to_inspect):
    '''
    Drops to ipython at the point in the code where it is called to inspect the variables passed to it.

    Parameters
    ----------
    local_variables : list
      Usually one would pass the output of locals().
    variables_to_inspect: tuple
      All variables passed to this routine are wrapped into a tuple.
    '''

    try:
        call_name = local_variables['self'].__module__
    except Exception:
        call_name = "Module"

    b = 'Dropping into IPython'
    em = 'Leaving Interpreter, back to program.'
    msg = '***Called from %s. Hit Ctrl-D to exit interpreter and continue program.'
    ipshell = InteractiveShellEmbed([], banner1=b, exit_msg=em)
    ipshell(msg % (call_name))
Exemple #56
0
def embed(**kwargs):  #reimplementation of embed that can handle threads
    """ see IPython.terminal.embed for original impelmentation
        the only addition is check_same_thread=False to allow
        sqlite3 to exit property at shutdown
    """
    config = kwargs.get('config')
    header = kwargs.pop('header', '')
    compile_flags = kwargs.pop('compile_flags', None)
    if config is None:
        config = load_default_config()
        config.InteractiveShellEmbed = config.TerminalInteractiveShell
        kwargs['config'] = config
    shell = InteractiveShellEmbed.instance(**kwargs)
    #/* added start
    hist_kwargs = dict(
        detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
        check_same_thread=False,  #XXX THIS
    )
    shell.history_manager.db = sqlite3.connect(shell.history_manager.hist_file,
                                               **hist_kwargs)
    # added end */
    shell(header=header, stack_depth=2, compile_flags=compile_flags)
Exemple #57
0
def ipython(user_ns=None):
    ipydir = os.path.join(cache_dir, 'ipython')
    os.environ['IPYTHONDIR'] = ipydir
    BANNER = ('Welcome to the interactive vise shell!\n')
    from IPython.terminal.embed import InteractiveShellEmbed
    from traitlets.config.loader import Config
    from IPython.terminal.prompts import Prompts, Token

    class CustomPrompt(Prompts):

        def in_prompt_tokens(self, cli=None):
            return [
                (Token.Prompt, 'vise['),
                (Token.PromptNum, str_version),
                (Token.Prompt, ']> '),
            ]

        def out_prompt_tokens(self):
            return []

    defns = {'os': os, 're': re, 'sys': sys}
    defns.update(user_ns or {})

    c = Config()
    c.TerminalInteractiveShell.prompts_class = CustomPrompt
    c.InteractiveShellApp.exec_lines = [
        'from __future__ import division, absolute_import, unicode_literals, print_function',
    ]
    c.TerminalInteractiveShell.confirm_exit = False
    c.TerminalInteractiveShell.banner1 = BANNER
    c.BaseIPythonApplication.ipython_dir = ipydir

    c.InteractiveShell.separate_in = ''
    c.InteractiveShell.separate_out = ''
    c.InteractiveShell.separate_out2 = ''

    ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns)
    ipshell()
Exemple #58
0
 def start(self):
     ipshell = InteractiveShellEmbed(
         banner1="\033[95mWelcome to the DBShell!\033[0m",
         banner2="\033[95mThis is an interactive shell to manipulate your "
         "documents through iu_mongo driver\033[0m")
     connection = self._connect
     h = self._help
     show_collections = self._show_collections
     command_docs = [
         '\033[94mconnection() -> get the current mongodb connection information\033[0m',
         '\033[94mconnection(host, db, username, password, auth_db) -> re-connect to a new mongodb host and db\033[0m',
         '\033[94mpp(doc) -> show the document information\033[0m',
         '\033[94mh() -> get help information\033[0m',
         '\033[94mshow_collections() -> get all defined document classes to manipulate\033[0m'
     ]
     self._help_info = BANNER % {
         'commands':
         '\n\n'.join('\t%s' % command_doc for command_doc in command_docs)
     }
     self._connect(self._host, self._db, self._username, self._password,
                   self._auth_db)
     ipshell(self._help_info + "\n\n" +
             self._show_collections(display=False))
Exemple #59
0
def start_python_console(namespace=None, noipython=False, banner=''):
    """Start Python console binded to the given namespace. If IPython is
    available, an IPython console will be started instead, unless `noipython`
    is True. Also, tab completion will be used on Unix systems.
    """
    if namespace is None:
        namespace = {}

    try:
        try: # use IPython if available
            if noipython:
                raise ImportError()

            try:
                import IPython
                if IPython.version_info[0] >= 1:
                    from IPython.terminal.embed import InteractiveShellEmbed
                else:
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                sh = InteractiveShellEmbed(banner1=banner)
            except ImportError:
                from IPython.Shell import IPShellEmbed
                sh = IPShellEmbed(banner=banner)

            sh(global_ns={}, local_ns=namespace)
        except ImportError:
            import code
            try: # readline module is only available on unix systems
                import readline
            except ImportError:
                pass
            else:
                import rlcompleter
                readline.parse_and_bind("tab:complete")
            code.interact(banner=banner, local=namespace)
    except SystemExit: # raised when using exit() in python code.interact
        pass
Exemple #60
0
 def runPlugin(self):
     '''
     The most simplest plugin! Just prints the tor data structure.
     '''
     try:
         get_ipython
     except NameError:
         nested = 0
         cfg = Config()
         prompt_config = cfg.PromptManager
         prompt_config.in_template = 'Tortazo Plugin <%s> : ' % (
             self.pluginLoaded)
         prompt_config.in2_template = "Type 'self.help()' to get information about the functions available in this plugin :"
     else:
         cfg = Config()
         nested = 1
     tortazoShell = InteractiveShellEmbed(
         config=cfg,
         banner1='Loading Tortazo plugin interpreter... ',
         banner2=
         "Plugin %s loaded successfully! Type self.help() to get information about this plugin and exit() to finish the execution. "
         % (self.pluginLoaded),
         exit_msg='Leaving Tortazo plugin interpreter.')
     tortazoShell()