execs a func and returns requested local vars.

    Does not modify globals unless update=True (or in IPython)

    SeeAlso:
        ut.execstr_funckw
177582
def exec_func_src(func, globals_=None, locals_=None, key_list=None,
                  sentinal=None, update=None, keys=None, verbose=False,
                  start=None, stop=None):
    
    if keys is None:
        keys = key_list
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if update is None:
        update = ut.inIPython()
    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)])
    globals_new = globals_.copy()
    if locals_ is not None:
        globals_new.update(locals_)
        # globals_new.update({k: v for k, v in locals_.items()
        #                     if k not in globals_new})
    orig_globals = globals_new.copy()
    #six.exec_(sourcecode, globals_new, locals_)
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    six.exec_(sourcecode, globals_new)
    # Draw intermediate steps
    if keys is None:
        #return locals_
        # Remove keys created in function execution
        ut.delete_keys(globals_new, orig_globals.keys())
        if update:
            # update input globals?
            globals_.update(globals_new)
        # ~~ TODO autodetermine the keys from the function vars
        return globals_new
    else:
        if update:
            # update input globals?
            globals_.update(globals_new)
        #var_list = ut.dict_take(locals_, keys)
        var_list = ut.dict_take(globals_new, keys)
        return var_list
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_
1212031
def return_locals(func):
    ''''''

    @functools.wraps(func)
    def wrap(*args, **kwargs):
        frames = []

        def tracer(frame, event, arg): # pragma: no cover
            # coverage does not work in this function because the tracer
            # is deactivated here
            frames.append(frame)
            sys.settrace(old_tracer)
            if old_tracer is not None:
                return old_tracer(frame, event, arg)

        old_tracer = sys.gettrace()
        # tracer is activated on next call, return or exception
        sys.settrace(tracer)
        try:
            func(*args, **kwargs)
        finally:
            sys.settrace(old_tracer)
        assert len(frames) == 1
        argspec = inspect.getargspec(func)
        argnames = list(argspec.args)
        if argspec.varargs is not None:
            argnames.append(argspec.varargs)
        if argspec.keywords is not None:
            argnames.append(argspec.keywords)
        return {name: value for name, value in frames.pop(0).f_locals.items()
                if name not in argnames}

    return wrap
5660
function execSpawn(command, args, resultMsg, errorMsg) {
    return superspawn.spawn(command, args).then(function(result) {
        return resultMsg + result;
    }, function(error) {
        return errorMsg + error;
    });
}
169481
function extractFunctionCall(str) {
      var match = /(\w+)\((.*)\)/.exec(str);
      if (!match) throw new Error("Invalid click handler '"+str+"'");

      return {
        "method": match[1],
        "args": match[2].split(',')
      };
    }
651616
def interpret(code, in_vars):
    """"""
    try:
        result = eval(code, in_vars)
    except SyntaxError:
        pass  # exec code outside of exception context
    else:
        if result is not None:
            print(ascii(result))
        return  # don't also exec code
    exec_func(code, in_vars)
625140
def exec_proc(proc_name, *variables)
      vars =
        if variables.any? && variables.first.is_a?(Hash)
          variables.first.map { |k, v| "@#{k} = #{quote(v)}" }
        else
          variables.map { |v| quote(v) }
        end.join(', ')
      sql = "EXEC #{proc_name} #{vars}".strip
      log(sql, 'Execute Procedure') do
        result = @connection.execute_query_raw(sql)
        result.map! do |row|
          row = row.is_a?(Hash) ? row.with_indifferent_access : row
          yield(row) if block_given?
          row
        end
        result
      end
    end
39417
def _get_funcs(self):
        
        f = c_uint32()
        ioctl(self.fd, I2C_FUNCS, f)
        return f.value
3175
def _mkprox(funcname):
    

    def prox(*args, **kwargs):
        _init()
        return getattr(_module, funcname)(*args, **kwargs)

    return prox
757145
def visit_exec(self, node):
        """"""
        if node.locals:
            return "exec %s in %s, %s" % (
                node.expr.accept(self),
                node.locals.accept(self),
                node.globals.accept(self),
            )
        if node.globals:
            return "exec %s in %s" % (node.expr.accept(self), node.globals.accept(self))
        return "exec %s" % node.expr.accept(self)
310278
def remote(self, func, *args, xfer_func=None, **kwargs):
        """"""
        global HAS_BUFFER
        HAS_BUFFER = self.has_buffer
        if hasattr(func, 'extra_funcs'):
          func_name = func.name
          func_lines = []
          for extra_func in func.extra_funcs:
            func_lines += inspect.getsource(extra_func).split('\n')
            func_lines += ['']
          func_lines += filter(lambda line: line[:1] != '@', func.source.split('\n'))
          func_src = '\n'.join(func_lines)
        else:
          func_name = func.__name__
          func_src = inspect.getsource(func)
        args_arr = [remote_repr(i) for i in args]
        kwargs_arr = ["{}={}".format(k, remote_repr(v)) for k, v in kwargs.items()]
        func_src += 'output = ' + func_name + '('
        func_src += ', '.join(args_arr + kwargs_arr)
        func_src += ')\n'
        func_src += 'if output is None:\n'
        func_src += '    print("None")\n'
        func_src += 'else:\n'
        func_src += '    print(output)\n'
        time_offset = self.time_offset
        if self.adjust_for_timezone:
          time_offset -= time.localtime().tm_gmtoff
        func_src = func_src.replace('TIME_OFFSET', '{}'.format(time_offset))
        func_src = func_src.replace('HAS_BUFFER', '{}'.format(HAS_BUFFER))
        func_src = func_src.replace('BUFFER_SIZE', '{}'.format(BUFFER_SIZE))
        func_src = func_src.replace('IS_UPY', 'True')
        if DEBUG:
            print('----- About to send %d bytes of code to the pyboard -----' % len(func_src))
            print(func_src)
            print('-----')
        self.check_pyb()
        try:
            self.pyb.enter_raw_repl()
            self.check_pyb()
            output = self.pyb.exec_raw_no_follow(func_src)
            if xfer_func:
                xfer_func(self, *args, **kwargs)
            self.check_pyb()
            output, _ = self.pyb.follow(timeout=20)
            self.check_pyb()
            self.pyb.exit_raw_repl()
        except (serial.serialutil.SerialException, TypeError):
            self.close()
            raise DeviceError('serial port %s closed' % self.dev_name_short)
        if DEBUG:
            print('-----Response-----')
            print(output)
            print('-----')
        return output
58323
def _execute(self, func, command, **new_attributes):
        
        if self._cfg_factory:
            # if we have a cfg_factory
            try:
                # we try to load a config with the factory
                if self.cfg_file:
                    self.cfg = self._cfg_factory(self.cfg_file)
            except Exception as error:
                # raise se exception
                self._cfg_error(error)
        # let's get command(function) argspec
        arg_specs = inspect.getargspec(command)
        if arg_specs.defaults:
            # if we have defaults
            # count defaults arguments
            count = len(arg_specs.defaults)
            # get arguments names
            args_names = arg_specs.args[:count]
            # get keyword arguments names
            kwargs_name = arg_specs.args[count:]
        else:
            # else all names are the args only
            args_names = arg_specs.args
            # and keyword arguments is empty
            kwargs_name = []
        pargs = []
        kwargs = {}
        # for every argument in argument names
        for name in args_names:
            if name == 'args':
                # if argument name is *special name* **args**
                # we append a reference to self.args
                pargs.append(self.args)
            elif name == 'self':
                # else if argment name is *special name* **self**
                if ArgParseInated in inspect.getmro(func.__cls__):
                    # if the class that holds the function is subclass of
                    # ArgParseInated we'll instantiate it, passing some
                    # parameter
                    pargs.append(func.__cls__(self, **new_attributes))
                else:
                    # else we'll instatiate the class without parameters
                    pargs.append(func.__cls__())
            else:
                # else we'll append the argument getting it from the self.args
                pargs.append(getattr(self.args, name))
        # for every argument in keyword arguments
        for name in kwargs_name:
            if name == 'args':
                # if argument name is *special name* **args**
                # we set for the arg a reference to self.args
                kwargs[name] = self.args
            elif name in self.args:
                # else if name is in self.args we'll set the relative value.
                kwargs[name] = getattr(self.args, name)
        # set the **global** write function
        setattr(__builtin__, self._write_name, self.write)
        # set the **global** write line function
        setattr(__builtin__, self._write_line_name, self.writeln)
        # let's setup something.
        for setup_func in self.setup:
            setup_func(self)
        # call event before_execute
        self._self_event('before_execute', command, *pargs, **kwargs)
        # if events returns a non None value we use it as retrval.
        retval, pargs, kwargs = self._call_event(
            'before_execute', command, pargs, kwargs)
        # if before_execute event returns None go on with command
        if retval is None:
            # let's execute the command and assign the returned value to retval
            retval = command(*pargs, **kwargs)
            # call event after_execute
            self._call_event('after_execute', command, pargs, kwargs)
            self._self_event('after_execute', command, *pargs, **kwargs)
        if self.auto_exit:
            # if we have auto_exit is True
            if retval is None:
                self._self_event(
                    'before_exit_ok', command, retval=EXIT_OK, *pargs, **kwargs)
                # if retval is None we'll assume it's EXIT_OK
                self.exit(EXIT_OK)
            elif isinstance(retval, basestring):
                self._self_event('before_exit_ok', command, retval=retval, *pargs, **kwargs)
                # else if retval is a string we will exit with the message and
                # ERRORCODE is equal to 0
                self.exit(EXIT_OK, retval)
            elif isinstance(retval, int):
                if retval == EXIT_OK:
                    self._self_event('before_exit_ok', command, retval=retval, *pargs, **kwargs)
                else:
                    self._self_event('before_exit_error', command, retval=retval, *pargs, **kwargs)
                # else if retval is an integer we'll exits with it as ERRORCODE
                self.exit(retval)
            elif isinstance(retval, (tuple, list,)):
                self._self_event('before_exit_error', command, retval=retval, *pargs, **kwargs)
                # if retval is a tuple or a list we'll exist with ERRORCODE and
                # message
                self.exit(retval[0], retval[1])
            self._self_event('before_exit', command, retval=retval, *pargs, **kwargs)
            self.exit()
        else:
            # else if auto_exit is not True
            # we'll simply return  retval
            return retval
533435
def global_variable_action(self, text, loc, var):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("GLOBAL_VAR:",var)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        index = self.symtab.insert_global_var(var.name, var.type)
        self.codegen.global_var(var.name)
        return index
1130261
def local_variable_action(self, text, loc, var):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("LOCAL_VAR:",var, var.name, var.type)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        index = self.symtab.insert_local_var(var.name, var.type, self.shared.function_vars)
        self.shared.function_vars += 1
        return index
924033
def run_func(self, func, load):
        '''
        
        '''
        # Don't honor private functions
        if func.startswith('__'):
            # TODO: return some error? Seems odd to return {}
            return {}, {'fun': 'send'}
        # Run the func
        if hasattr(self, func):
            try:
                start = time.time()
                ret = getattr(self, func)(load)
                log.trace(
                    'Master function call %s took %s seconds',
                    func, time.time() - start
                )
            except Exception:
                ret = ''
                log.error('Error in function %s:\n', func, exc_info=True)
        else:
            log.error(
                'Received function %s which is unavailable on the master, '
                'returning False', func
            )
            return False, {'fun': 'send'}
        # Don't encrypt the return value for the _return func
        # (we don't care about the return value, so why encrypt it?)
        if func == '_return':
            return ret, {'fun': 'send'}
        if func == '_pillar' and 'id' in load:
            if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
                # Authorized to return old pillar proto
                return ret, {'fun': 'send'}
            return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
        # Encrypt the return
        return ret, {'fun': 'send'}
1178860
function checkExecPath (execPath, errorCallback) {
    this.log.verbose(`- executing "${execPath}" to get version`)
    this.run(execPath, this.argsVersion, false, function (err, version) {
      // Possible outcomes:
      // - Error: executable can not be run (likely meaning the command wasn't
      //   a Python executable and the previous command produced gibberish)
      // - Gibberish: somehow the last command produced an executable path,
      //   this will fail when verifying the version
      // - Version of the Python executable
      if (err) {
        this.addLog(`- "${execPath}" could not be run`)
        return errorCallback(err)
      }
      this.addLog(`- version is "${version}"`)

      const range = semver.Range(this.semverRange)
      var valid = false
      try {
        valid = range.test(version)
      } catch (err) {
        this.log.silly('range.test() threw:\n%s', err.stack)
        this.addLog(`- "${execPath}" does not have a valid version`)
        this.addLog('- is it a Python executable?')
        return errorCallback(err)
      }

      if (!valid) {
        this.addLog(`- version is ${version} - should be ${this.semverRange}`)
        this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED')
        return errorCallback(new Error(
          `Found unsupported Python version ${version}`))
      }
      this.succeed(execPath, version)
    }.bind(this))
  }
1342440
def get_func_params(method, called_params):
    
    insp = inspect.getfullargspec(method)
    if not isinstance(called_params, dict):
        raise UserWarning()
    _called_params = called_params.copy()
    params = {}
    arg_count = len(insp.args)
    arg_def_count = len(insp.defaults) if insp.defaults is not None else 0
    for i in range(arg_count):
        arg = insp.args[i]
        if i == 0 and isinstance(method, types.MethodType):
            continue  # skip self argument
        if arg in _called_params:
            params[arg] = _called_params.pop(arg)
        elif i - arg_count + arg_def_count >= 0:
            params[arg] = insp.defaults[i - arg_count + arg_def_count]
        else:
            raise TypeError('Argument "%s" not given' % arg)
    for kwarg in insp.kwonlyargs:
        if kwarg in _called_params:
            params[kwarg] = _called_params.pop(kwarg)
        elif kwarg in insp.kwonlydefaults:
            params[kwarg] = insp.kwonlydefaults[kwarg]
        else:
            raise TypeError('Argument "%s" not given' % kwarg)
    if insp.varkw is None:
        if len(_called_params) > 0:
            raise TypeError('Got unexpected parameter(s): %s'
                            '' % (", ".join(_called_params)))
    else:
        params.update(_called_params)
    return params