Ejemplo n.º 1
0
def entry_point():
    west = WIPI()
    w = west
    # We're gonna print some defaults.
    w.main()
    if w.analysis_mode is False:
        from IPython import embed
        import IPython

        # We're using this to set magic commands.
        # Mostly, we're using it to allow tab completion of objects stored in dictionaries.
        try:
            # Worked on MacOS.  Probably just an older version.
            c = IPython.Config()
        except Exception:
            # Seems to be necessary on Linux, and likely on newer installs.
            c = IPython.terminal.ipapp.load_default_config()
        c.IPCompleter.greedy = True
        embed(banner1='', exit_msg='Leaving w_ipa... goodbye.', config=c)
    print("")
Ejemplo n.º 2
0
def embed_interactive(**kwargs):
    """Embed an interactive terminal into a running python process
    """
    if 'state' not in kwargs:
        kwargs['state'] = state
    if 'conf' not in kwargs:
        kwargs['conf'] = conf

    try:
        import IPython
        ipython_config = IPython.Config()
        ipython_config.TerminalInteractiveShell.confirm_exit = False
        if int(IPython.__version__.split(".")[0]) < 3:
            IPython.embed(config=ipython_config, banner1='', user_ns=kwargs)
        else:
            IPython.embed(config=ipython_config, banner1='', local_ns=kwargs)
    except ImportError:
        import readline  # pylint: disable=unused-variable
        import code

        code.InteractiveConsole(kwargs).interact()
Ejemplo n.º 3
0
        return_list = ['past', 'current', 'future']
        # For the moment, don't expose direct, reweight, or assign, as these are scheme dependent files.
        # They do exist, and always link to the current scheme, however.
        return_list += ['iteration', 'niters', 'scheme', 'list_schemes', 'bin_labels', 'state_labels', 'west', 'trace']
        return sorted(set(return_list))



west = WIPI()
w = west
if __name__ == '__main__':
    # We're gonna print some defaults.
    w.main()
    if w.analysis_mode == False:
        from IPython import embed, embed_kernel
        from IPython.lib.kernel import find_connection_file
        import IPython
        # We're using this to set magic commands.
        # Mostly, we're using it to allow tab completion of objects stored in dictionaries.
        try:
            # Worked on MacOS.  Probably just an older version.
            c = IPython.Config()
        except:
            # Seems to be necessary on Linux, and likely on newer installs.
            c = IPython.terminal.ipapp.load_default_config()
        c.IPCompleter.greedy = True
        embed(banner1='',
             exit_msg='Leaving w_ipa... goodbye.',
             config=c)
    print("")
Ejemplo n.º 4
0
def embed(parent_locals=None, parent_globals=None, exec_lines=None,
          remove_pyqt_hook=True, N=0):
    """
    Starts interactive session. Similar to keyboard command in matlab.
    Wrapper around IPython.embed

    Notes:
        #https://github.com/ipython/ipython/wiki/Cookbook%3a-Updating-code-for-use-with-IPython-0.11-and-later

        import IPython
        x = 3
        IPython.embed()
        c = IPython.Config()
        c.InteractiveShellApp.exec_lines = [
            '%pylab qt4',
            "print 'System Ready!'",
        ]

        def foo():
            return x + 3

        a = 3
        def bar():
            return a + 3
        bar()
        #NameError: global name 'a' is not defined


        from IPython.terminal.ipapp import TerminalIPythonApp
        x = 3
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[]) # argv=[] instructs IPython to ignore sys.argv
        app.start()


    Args:
        parent_locals (None):
        parent_globals (None):
        exec_lines (None):
        remove_pyqt_hook (bool):
        N (int):

    CommandLine:
        python -m utool.util_dbg --test-embed

    References:
       http://stackoverflow.com/questions/27911570/can-you-specify-a-command-to-run-after-you-embed-into-ipython/27914204#27914204
       http://stackoverflow.com/questions/15167200/how-do-i-embed-an-ipython-interpreter-into-an-application-running-in-an-ipython

    TODO:
        try:
            get_ipython
        except NameError:
            banner=exit_msg=''
        else:
            banner = '*** Nested interpreter ***'
            exit_msg = '*** Back in main IPython ***'

        # First import the embed function
        from IPython.frontend.terminal.embed import InteractiveShellEmbed
        # Now create the IPython shell instance. Put ipshell() anywhere in your code
        # where you want it to open.
        ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
        #Then use ipshell() whenever you want to be dropped into an IPython shell. This
        #will allow you to embed (and even nest) IPython interpreters in your code and
        #inspect objects or the state of the program.

    Example:
        >>> # DISABLE_DOCTEST
        >>> from utool.util_dbg import *  # NOQA
        >>> # build test data
        >>> parent_locals = None
        >>> parent_globals = None
        >>> exec_lines = None
        >>> remove_pyqt_hook = True
        >>> N = 0
        >>> # execute function
        >>> result = embed(parent_locals, parent_globals, exec_lines, remove_pyqt_hook, N)
        >>> # verify results
        >>> print(result)
    """
    import utool as ut
    from functools import partial
    import IPython

    if parent_globals is None:
        parent_globals = get_parent_globals(N=N)
        #parent_globals1 = get_parent_globals(N=0)
        #exec(execstr_dict(parent_globals1, 'parent_globals1'))
    if parent_locals is None:
        parent_locals = get_parent_locals(N=N)

    stackdepth = N  # NOQA
    getframe = partial(ut.get_caller_stack_frame, N=N)  # NOQA

    exec(execstr_dict(parent_globals, 'parent_globals'))
    exec(execstr_dict(parent_locals,  'parent_locals'))
    print('')
    print('================')
    print(ut.bubbletext('EMBEDDING'))
    print('================')
    print('[util] embedding')
    try:
        if remove_pyqt_hook:
            try:
                import guitool
                guitool.remove_pyqt_input_hook()
            except (ImportError, ValueError, AttributeError) as ex:
                #print(ex)
                printex(ex, iswarning=True)
                pass
            # make qt not loop forever (I had qflag loop forever with this off)
    except ImportError as ex:
        print(ex)
    NEW_METHOD = False
    if NEW_METHOD:
        user_ns = globals()
        user_ns = globals().copy()
        user_ns.update(locals())
        if parent_globals is not None:
            user_ns.update(parent_globals)
        if parent_locals is not None:
            user_ns.update(parent_locals)
        orig_argv = sys.argv  # NOQA
        print('About to start_ipython')
        config = IPython.Config()
        exec_lines_ = [
            '%pylab qt4',
            'print("Entered IPYTHON via utool")',
            'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=11).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=10).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=9).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=8).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=7).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=6).f_code.co_name,))',
            #'print("Entry Point: %r" % (ut.get_caller_stack_frame(N=5).f_code.co_name,))',
            #execstr_dict(parent_locals)
        ] + ut.ensure_str_list(exec_lines if exec_lines is not None else [])
        config.InteractiveShellApp.exec_lines = exec_lines_
        print('Exec Lines: ')
        print(ut.indentjoin(exec_lines_, '\n    >>> '))
        IPython.start_ipython(config=config, argv=[], user_ns=user_ns)
        # Exit python immediately if specifed
        if user_ns.get('qqq', False) or vars.get('qqq', False) or user_ns.get('EXIT_NOW', False):
            print('[utool.embed] EXIT_NOW or qqq specified')
            sys.exit(1)
    else:
        #from IPython.config.loader import Config
        # cfg = Config()
        #config_dict = {}
        #if exec_lines is not None:
        #    config_dict['exec_lines'] = exec_lines
        #IPython.embed(**config_dict)
        print('[util]  Get stack location with: ')
        print('[util] ut.get_caller_stack_frame(N=8).f_code.co_name')
        print('[util] set EXIT_NOW or qqq to True(ish) to hard exit on unembed')
        #print('set iup to True to draw plottool stuff')
        print('[util] call %pylab qt4 to get plottool stuff working')
        once = True
        # Allow user to set iup and redo the loop
        while once or vars().get('iup', False):
            if not once:
                # SUPER HACKY WAY OF GETTING FIGURES ON THE SCREEN BETWEEN UPDATES
                #vars()['iup'] = False
                # ALL YOU NEED TO DO IS %pylab qt4
                print('re-emebeding')
                #import plottool as pt
                #pt.update()
                #(pt.present())
                for _ in range(100):
                    time.sleep(.01)

            once = False
            #vars().get('iup', False):
            print('[util] calling IPython.embed()')
            """
            Notes:
                /usr/local/lib/python2.7/dist-packages/IPython/terminal/embed.py
                IPython.terminal.embed.InteractiveShellEmbed

                # instance comes from  IPython.config.configurable.SingletonConfigurable.instance
            """
            #c = IPython.Config()
            #c.InteractiveShellApp.exec_lines = [
            #    '%pylab qt4',
            #    "print 'System Ready!'",
            #]
            #IPython.embed(config=c)
            try:
                IPython.embed()
            except RuntimeError as ex:
                ut.printex(ex, 'Failed to open ipython')
            #config = IPython.terminal.ipapp.load_default_config()
            #config.InteractiveShellEmbed = config.TerminalInteractiveShell
            #module = sys.modules[parent_globals['__name__']]
            #config['module'] = module
            #config['module'] = module
            #embed2(stack_depth=N + 2 + 1)
            #IPython.embed(config=config)
            #IPython.embed(config=config)
            #IPython.embed(module=module)
            # Exit python immediately if specifed
            if vars().get('EXIT_NOW', False) or vars().get('qqq', False):
                print('[utool.embed] EXIT_NOW specified')
                sys.exit(1)