Called by remote workers. Useful to populate main module globals()
        for interactive shells. Retrieves the serialized function.
344983
def getFunction(self):
        """"""
        return functionFactory(
            self.code,
            self.name,
            self.defaults,
            self.globals,
            self.imports,
        )
505613
def entry_point(__func: Callable) -> Callable:
    
    if __func.__module__ == '__main__':
        import sys
        sys.exit(__func())
    else:
        return __func
834203
def globalize(self):
        
        try:
            with open(os.path.join(self.dirPath, '.stash')) as f:
                fromVirtualEnv = [False, True][int(f.read(1))]
                dirPath = f.read()
        except IOError as e:
            if e.errno == errno.ENOENT:
                if self._runningOnWorker():
                    log.warn("Can't globalize module %r.", self)
                return self
            else:
                raise
        else:
            return self.__class__(dirPath=dirPath,
                                  name=self.name,
                                  fromVirtualEnv=fromVirtualEnv)
184629
def save_global(self, obj, name=None, pack=struct.pack):
        
        if obj.__module__ == "__builtin__" or obj.__module__ == "builtins":
            if obj in _BUILTIN_TYPE_NAMES:
                return self.save_reduce(_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)

        if name is None:
            name = obj.__name__

        modname = getattr(obj, "__module__", None)
        if modname is None:
            try:
                # whichmodule() could fail, see
                # https://bitbucket.org/gutworth/six/issues/63/importing-six-breaks-pickling
                modname = pickle.whichmodule(obj, name)
            except Exception:
                modname = '__main__'

        if modname == '__main__':
            themodule = None
        else:
            __import__(modname)
            themodule = sys.modules[modname]
            self.modules.add(themodule)

        if hasattr(themodule, name) and getattr(themodule, name) is obj:
            return Pickler.save_global(self, obj, name)

        typ = type(obj)
        if typ is not obj and isinstance(obj, (type, _class_type)):
            self.save_dynamic_class(obj)
        else:
            raise pickle.PicklingError("Can't pickle %r" % obj)
99617
def exec_func_src2(func, globals_=None, locals_=None, sentinal=None,
                   verbose=False, start=None, stop=None):
    
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if globals_ is None:
        globals_ = ut.get_parent_frame().f_globals
    if locals_ is None:
        locals_ = ut.get_parent_frame().f_locals
    if sentinal is not None:
        sourcecode = ut.replace_between_tags(sourcecode, '', sentinal)
    if start is not None or stop is not None:
        sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)])
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    # TODO: find the name of every variable that was assigned in the function
    # and get it from the context
    locals2_ = locals_.copy()
    globals2_ = globals_.copy()
    six.exec_(sourcecode, globals2_, locals2_)
    return locals2_
1267095
def get_handle():
    '''
    
    '''
    global __handle__
    if not __handle__:
        __handle__ = FT_Library()
        error = FT_Init_FreeType(byref(__handle__))
        if error:
            raise RuntimeError(hex(error))
    return __handle__
12345
def eval_py(self, _globals, _locals):
        
        try:
            params = eval(self.script, _globals, _locals)
        except NameError as e:
            raise Exception(
                'Failed to evaluate parameters: {}'
                .format(str(e))
            )
        except ResolutionError as e:
            raise Exception('GetOutput: {}'.format(str(e)))

        return params
1194533
def run_module(mod_name, init_globals=None,
               run_name=None, alter_sys=False):
    
    mod_name, loader, code, fname = _get_module_details(mod_name)
    if run_name is None:
        run_name = mod_name
    pkg_name = mod_name.rpartition('.')[0]
    if alter_sys:
        return _run_module_code(code, init_globals, run_name,
                                fname, loader, pkg_name)
    else:
        # Leave the sys module alone
        return _run_code(code, {}, init_globals, run_name,
                         fname, loader, pkg_name)
955524
def call_plac(f):
    ""
    name = inspect.currentframe().f_back.f_globals['__name__']
    if name == '__main__':
        import plac
        res = plac.call(f)
        if callable(res): res()
    else: return f
778733
def _getGlobals(self, **kwargs):
        
        # Default globals
        globs = {
            "__builtins__": None,
            "all": all,
            "any": any,
            "bool": bool,
            "chr": chr,
            "cmp": cmp,
            "complex": complex,
            "divmod": divmod,
            "enumerate": enumerate,
            "float": float,
            "format": format,
            "frozenset": frozenset,
            "hex": hex,
            "int": int,
            "len": len,
            "list": list,
            "long": long,
            "math": math,
            "max": max,
            "min": min,
            "oct": oct,
            "ord": ord,
            "pow": pow,
            "range": range,
            "reversed": reversed,
            "round": round,
            "str": str,
            "sum": sum,
            "tuple": tuple,
            "xrange": xrange,
        }
        # Update with keyword arguments
        globs.update(kwargs)
        # Update with additional Python libraries
        for imp in self.getPythonImports():
            mod = imp["module"]
            func = imp["function"]
            member = self._getModuleMember(mod, func)
            if member is None:
                raise ImportError(
                    "Could not find member {} of module {}".format(
                        func, mod))
            globs[func] = member
        return globs
841294
def extract_func_data(self, func):
        
        code = func.__code__

        # extract all global ref's
        func_global_refs = self.extract_code_globals(code)

        # process all variables referenced by global environment
        f_globals = {}
        for var in func_global_refs:
            if var in func.__globals__:
                f_globals[var] = func.__globals__[var]

        # defaults requires no processing
        defaults = func.__defaults__

        # process closure
        closure = (
            list(map(_get_cell_contents, func.__closure__))
            if func.__closure__ is not None
            else None
        )

        # save the dict
        dct = func.__dict__

        base_globals = self.globals_ref.get(id(func.__globals__), None)
        if base_globals is None:
            # For functions defined in a well behaved module use
            # vars(func.__module__) for base_globals. This is necessary to
            # share the global variables across multiple pickled functions from
            # this module.
            if hasattr(func, '__module__') and func.__module__ is not None:
                base_globals = func.__module__
            else:
                base_globals = {}
        self.globals_ref[id(func.__globals__)] = base_globals

        return (code, f_globals, defaults, closure, dct, base_globals)
937368
def thread_global(name, default_value = nil)
      is_a?(Module) or raise TypeError, "receiver has to be a Module"

      name = name.to_s
      var_name = "@__#{name}_#{__id__.abs}__"

      lock = Mutex.new
      modul = self

      define_method(name) do
        lock.synchronize { modul.instance_variable_get var_name }
      end

      define_method(name + "=") do |value|
        lock.synchronize { modul.instance_variable_set var_name, value }
      end

      modul.instance_variable_set var_name, default_value if default_value
      self
    end
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)
1065628
def get_globals(self):
        """"""
        if self.shell:
            globals_ = dict(_initial_globals)
        else:
            globals_ = dict(self.current_frame.f_globals)
        globals_['_'] = self.db.last_obj
        if cut is not None:
            globals_.setdefault('cut', cut)
        # For meta debuging purpose
        globals_['___wdb'] = self.db
        # Hack for function scope eval
        globals_.update(self.current_locals)
        for var, val in self.db.extra_vars.items():
            globals_[var] = val
        self.db.extra_items = {}
        return globals_
1021573
def _make_skel_func(code, cell_count, base_globals=None):
    
    if base_globals is None:
        base_globals = {}
    elif isinstance(base_globals, string_types):
        base_globals_name = base_globals
        try:
            # First try to reuse the globals from the module containing the
            # function. If it is not possible to retrieve it, fallback to an
            # empty dictionary.
            if importlib is not None:
                base_globals = vars(importlib.import_module(base_globals))
            elif sys.modules.get(base_globals, None) is not None:
                base_globals = vars(sys.modules[base_globals])
            else:
                raise ImportError
        except ImportError:
            base_globals = _dynamic_modules_globals.get(
                    base_globals_name, None)
            if base_globals is None:
                base_globals = _DynamicModuleFuncGlobals()
            _dynamic_modules_globals[base_globals_name] = base_globals

    base_globals['__builtins__'] = __builtins__

    closure = (
        tuple(_make_empty_cell() for _ in range(cell_count))
        if cell_count >= 0 else
        None
    )
    return types.FunctionType(code, base_globals, None, None, closure)
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
370393
def interactive_shell():
    
    print('You should be able to read and update the "counter[0]" variable from this shell.')
    try:
        yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)
    except EOFError:
        # Stop the loop when quitting the repl. (Ctrl-D press.)
        loop.stop()