Return a interactive python console instance with caller's stack
776014
def get_python_console(namespace=None):
    

    if namespace is None:
        import inspect
        frame = inspect.currentframe()
        caller = frame.f_back
        if not caller:
            logging.error("can't find caller who start this console.")
            caller = frame
        namespace = dict(caller.f_globals)
        namespace.update(caller.f_locals)

    try:
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        shell = TerminalInteractiveShell(user_ns=namespace)
    except ImportError:
        try:
            import readline
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(namespace).complete)
            readline.parse_and_bind("tab: complete")
        except ImportError:
            pass
        import code
        shell = code.InteractiveConsole(namespace)
        shell._quit = False

        def exit():
            shell._quit = True

        def readfunc(prompt=""):
            if shell._quit:
                raise EOFError
            return six.moves.input(prompt)

        # inject exit method
        shell.ask_exit = exit
        shell.raw_input = readfunc

    return shell
118456
def python(source):
    
    """
    obj = type('', (object,), {})()
    _exec(source, obj.__dict__, obj.__dict__)
    return obj
283125
def console(cls, id):
        """"""
        oper = cls.call('paas.update', cls.usable_id(id), {'console': 1})
        cls.echo('Activation of the console on your PaaS instance')
        cls.display_progress(oper)
        console_url = Paas.info(cls.usable_id(id))['console']
        access = 'ssh %s' % console_url
        cls.execute(access)
919176
def main(
    output_file: str,
    entry_point: Optional[str],
    console_script: Optional[str],
    python: Optional[str],
    site_packages: Optional[str],
    compressed: bool,
    compile_pyc: bool,
    extend_pythonpath: bool,
    pip_args: List[str],
) -> None:
    

    if not pip_args and not site_packages:
        sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES)

    if output_file is None:
        sys.exit(NO_OUTFILE)

    # check for disallowed pip arguments
    for disallowed in DISALLOWED_ARGS:
        for supplied_arg in pip_args:
            if supplied_arg in disallowed:
                sys.exit(
                    DISALLOWED_PIP_ARGS.format(
                        arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed]
                    )
                )

    with TemporaryDirectory() as working_path:
        tmp_site_packages = Path(working_path, "site-packages")

        if site_packages:
            shutil.copytree(site_packages, tmp_site_packages)

        if pip_args:
            # install deps into staged site-packages
            pip.install(["--target", str(tmp_site_packages)] + list(pip_args))

        # if entry_point is a console script, get the callable
        if entry_point is None and console_script is not None:
            try:
                entry_point = find_entry_point(tmp_site_packages, console_script)

            except KeyError:
                if not Path(tmp_site_packages, "bin", console_script).exists():
                    sys.exit(NO_ENTRY_POINT.format(entry_point=console_script))

        # create runtime environment metadata
        env = Environment(
            build_id=str(uuid.uuid4()),
            entry_point=entry_point,
            script=console_script,
            compile_pyc=compile_pyc,
            extend_pythonpath=extend_pythonpath,
        )

        Path(working_path, "environment.json").write_text(env.to_json())

        # create bootstrapping directory in working path
        bootstrap_target = Path(working_path, "_bootstrap")
        bootstrap_target.mkdir(parents=True, exist_ok=True)

        # copy bootstrap code
        copy_bootstrap(bootstrap_target)

        # create the zip
        builder.create_archive(
            Path(working_path),
            target=Path(output_file).expanduser(),
            interpreter=python or _interpreter_path(),
            main="_bootstrap:bootstrap",
            compressed=compressed,
        )
11493
def interact_plain(header=UP_LINE, local_ns=None,
                   module=None, dummy=None,
                   stack_depth=1, global_ns=None):
    
    frame = sys._getframe(stack_depth)

    variables = {}

    if local_ns is not None:
        variables.update(local_ns)
    else:
        variables.update(frame.f_locals)

    if global_ns is not None:
        variables.update(local_ns)
    else:
        variables.update(frame.f_globals)

    shell = code.InteractiveConsole(variables)
    return shell.interact(banner=header)
1027731
def console_new(w: int, h: int) -> tcod.console.Console:
    
    return tcod.console.Console(w, h)
239024
def cli(ctx):
    
    level = logger.level
    try:
        level_to_name = logging._levelToName
    # Fallback to pre-Python 3.4 internals.
    except AttributeError:
        level_to_name = logging._levelNames
    level_name = level_to_name.get(level, level)
    logger.debug('Verbosity set to {}.'.format(level_name))

    # Print help screen and exit if no sub-commands provided.
    if ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
        ctx.exit()

    # Load up global options to the context.
    ctx.obj = {}
497975
def _get_or_create_stack(name):
  """"""
  stack = getattr(_LOCAL_STACKS, name, None)
  if stack is None:
    stack = []
    setattr(_LOCAL_STACKS, name, stack)
  return stack
881276
def move_in_stack(move_up):
    ''''''
    frame = Frame.get_selected_python_frame()
    while frame:
        if move_up:
            iter_frame = frame.older()
        else:
            iter_frame = frame.newer()

        if not iter_frame:
            break

        if iter_frame.is_evalframeex():
            # Result:
            if iter_frame.select():
                iter_frame.print_summary()
            return

        frame = iter_frame

    if move_up:
        print 'Unable to find an older python frame'
    else:
        print 'Unable to find a newer python frame'
479468
def embed(parent_locals=None, parent_globals=None, exec_lines=None,
          remove_pyqt_hook=True, N=0):
    
    import utool as ut
    from functools import partial
    import IPython

    if parent_globals is None:
        parent_globals = get_parent_frame(N=N).f_globals
    if parent_locals is None:
        parent_locals = get_parent_frame(N=N).f_locals

    stackdepth = N  # NOQA
    getframe = partial(ut.get_parent_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)

    #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_parent_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',
        #    '%gui qt4',
        #    "print 'System Ready!'",
        #]
        #IPython.embed(config=c)
        parent_ns = parent_globals.copy()
        parent_ns.update(parent_locals)
        locals().update(parent_ns)
        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)
657867
def get_caller_info(depth=2, trace=False):
    
    try:
        frame = inspect.stack()[depth]
    except:
        die("could not access the caller's frame at stack index %d" % depth)
    if trace:
        print_stack(frame[0].f_back)
    func = frame[3]
    module = inspect.getmodule(frame[0])
    if module:
        return (module.__name__, func)
    else:
        return ('<unknown>', func)
324963
def run_func(func, *args, **kwargs):
    """"""
    ray.init()

    func = ray.remote(func)

    # NOTE: kwargs not allowed for now
    result = ray.get(func.remote(*args))

    # Inspect the stack to get calling example
    caller = inspect.stack()[1][3]
    print("%s: %s" % (caller, str(result)))

    return result
399674
def console_main():
    """"""
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    parser.add_argument('-t', '--titles', action='store_true',
                        help='input files have column titles')
    parser.add_argument(
        '-j', '--join', choices=['inner', 'outer'],
        help=('The kind of left join to perform.  Outer join outputs left-hand '
              'rows which have no right hand match, while inner join discards '
              'such rows. Default: %(default)s'))
    parser.add_argument('-m', '--minscore', type=float,
                        help='Minimum match score: %(default)s')
    parser.add_argument('-c', '--count', type=int,
                help='Max number of rows to match (0 for all): %(default)s')
    parser.add_argument('-w', '--warp', type=float,
            help='N-gram warp, higher helps short strings: %(default)s')
    parser.add_argument('left', nargs=1, help='First CSV file')
    parser.add_argument('leftcolumn', nargs=1, type=int, help='Column in first CSV file')
    parser.add_argument('right', nargs=1, help='Second CSV file')
    parser.add_argument('rightcolumn', nargs=1, type=int, help='Column in second CSV file')
    parser.add_argument('outfile', nargs=1, help='Output CSV file')
    parser.set_defaults(
        titles=False, join='outer', minscore=0.24, count=0, warp=1.0)
    args = parser.parse_args()
    for path in [args.left[0], args.right[0]]:
        if not os.path.isfile(path):
            parser.error('File "%s" does not exist.' % path)
    if not (0 <= args.minscore <= 1.0):
        parser.error("Minimum score must be between 0 and 1")
    if not args.count >= 0:
        parser.error("Maximum number of matches per row must be non-negative.")
    if args.count == 0:
        args.count = None # to return all results
    main(args.left[0], args.leftcolumn[0], args.right[0], args.rightcolumn[0],
         args.outfile[0], args.titles, args.join, args.minscore, args.count,
         args.warp)
806519
def from_caller_module_root():
        ''''''
        import inspect
        all_stack = list(inspect.stack())
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 2)
        module = inspect.getmodule(calframe[1].frame)
        if not module:
            raise RuntimeError('caller is not a module')
        root_module_name = module.__name__.partition('.')[0]
        fullpath = sys.modules[root_module_name].__file__
        return Path(fullpath)
1152138
def launch(exception=None, extraceback=None, signalnum=None, frame=None):
    

    print('\n')
    print('Activating emergency console')
    print('----------------------------')

    print('Caused by:')
    if signalnum:
        signals = dict((k, v) for v, k in signal.__dict__.iteritems() if v.startswith('SIG'))
        print('Signal', signals.get(signalnum, 'unknown'))
    elif exception:
        print(exception.__class__.__name__)
        print(exception)
    else:
        print('manual invocation')

    stack = []
    locals = {}
    active_frame = 0
    if frame:
        current_frame = frame
        while current_frame:
            stack.insert(0, current_frame)
            current_frame = current_frame.f_back
    if extraceback:
        current_tb = extraceback
        while current_tb:
            stack.append(current_tb.tb_frame)
            current_tb = current_tb.tb_next

    import readline
    import code

    def _cmd_stack():
        index = 0
        print('\nStack frames:')
        for frame in stack:
            s = '> ' if (active_frame == index) else '  '
            s += '[%s] ' % str(index).rjust(3)
            lines, current_line = inspect.getsourcelines(frame)
            s += '%s:%i' % (inspect.getfile(frame), frame.f_lineno)
            s += '\n' + ' ' * 10
            if frame.f_lineno - current_line < len(lines):
                s += lines[frame.f_lineno - current_line].strip('\n')
            print(s)
            index += 1

    def _cmd_help():
        print((
            "Exconsole interactive emergency console\n"
            "Builtin commands:\n"
            " - _help()    this help\n"
            " - _s()       display stack\n"
            " - _f(index)  change current stack frame\n"
            " - _pdb()     launch PDB debugger\n"
            " - _exc       exception object\n"
            " - Ctrl-D     leave console\n"
        ))
        print('\n'.join(' - %s\t%s' % x[:2] for x in launch.commands))

    def _cmd_pdb():
        pdb.pm()

    def _cmd_frame(index):
        if not isinstance(index, int):
            print('index must be int')
            return
        if index < 0 or index >= len(stack):
            print('index out of bounds')
            return
        frame = stack[index] 
        locals.clear()
        locals.update(frame.f_locals)
        locals.update({
            '_help': _cmd_help,
            '_s': _cmd_stack,
            '_f': _cmd_frame,
            '_pdb': _cmd_pdb,
            '_exc': exception,
        })
        for command in launch.commands:
            locals[command[0]] = command[2]

        print('On frame %i' % index)
        print('Source:')

        lines, current_line = inspect.getsourcelines(frame)
        print(''.join(
            '    ' +
            ('>>' if lines.index(line) == frame.f_lineno - current_line else '  ') +
            ' ' + line
            for line in lines
        ))

    active_frame = len(stack) - 1
    _cmd_stack()
    _cmd_frame(len(stack) - 1)

    shell = code.InteractiveConsole(locals)

    print('Press Ctrl-D to leave console')
    print('Type "_help()" for built-in commands')

    shell.interact(banner='')
746632
def get_interactive_console(thread_id, frame_id, frame, console_message):
    
    if InteractiveConsoleCache.thread_id == thread_id and InteractiveConsoleCache.frame_id == frame_id:
        return InteractiveConsoleCache.interactive_console_instance

    InteractiveConsoleCache.interactive_console_instance = DebugConsole()
    InteractiveConsoleCache.thread_id = thread_id
    InteractiveConsoleCache.frame_id = frame_id

    console_stacktrace = traceback.extract_stack(frame, limit=1)
    if console_stacktrace:
        current_context = console_stacktrace[0] # top entry from stacktrace
        context_message = 'File "%s", line %s, in %s' % (current_context[0], current_context[1], current_context[2])
        console_message.add_console_message(CONSOLE_OUTPUT, "[Current context]: %s" % (context_message,))
    return InteractiveConsoleCache.interactive_console_instance
1305122
def inject_print_functions(module_name=None, module_prefix='[???]',
                           DEBUG=False, module=None):
    
    module = _get_module(module_name, module)
    if SILENT:
        def print(*args):
            """ silent builtins.print """
            pass
        def printDBG(*args):
            """ silent debug print """
            pass
        def print_(*args):
            """ silent stdout.write """
            pass
    else:
        if DEBUG_PRINT:
            # Turns on printing where a message came from
            def print(*args):
                """ debugging logging builtins.print """
                from utool._internal.meta_util_dbg import get_caller_name
                calltag = ''.join(('[caller:', get_caller_name(N=DEBUG_PRINT_N), ']' ))
                util_logging._utool_print()(calltag, *args)
        else:
            def print(*args):
                """ logging builtins.print """
                util_logging._utool_print()(*args)

        if __AGGROFLUSH__:
            def print_(*args):
                """ aggressive logging stdout.write """
                util_logging._utool_write()(*args)
                util_logging._utool_flush()()
        else:
            def print_(*args):
                """ logging stdout.write """
                util_logging._utool_write()(*args)

        # turn on module debugging with command line flags
        dotpos = module.__name__.rfind('.')
        if dotpos == -1:
            module_name = module.__name__
        else:
            module_name = module.__name__[dotpos + 1:]
        def _replchars(str_):
            return str_.replace('_', '-').replace(']', '').replace('[', '')
        flag1 = '--debug-%s' % _replchars(module_name)
        flag2 = '--debug-%s' % _replchars(module_prefix)
        DEBUG_FLAG = any([flag in sys.argv for flag in [flag1, flag2]])
        for curflag in ARGV_DEBUG_FLAGS:
            if curflag in module_prefix:
                DEBUG_FLAG = True
        if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG:
            print('INJECT_PRINT: %r == %r' % (module_name, module_prefix))
            def printDBG(*args):
                """ debug logging print """
                msg = ', '.join(map(str, args))
                util_logging.__UTOOL_PRINTDBG__(module_prefix + ' DEBUG ' + msg)
        else:
            def printDBG(*args):
                """ silent debug logging print """
                pass
    #_inject_funcs(module, print, print_, printDBG)
    print_funcs = (print, print_, printDBG)
    return print_funcs