Execute a command on a given module by its serial number
356460
async def execute_module_command(request):
    
    hw = hw_from_req(request)
    requested_serial = request.match_info['serial']
    data = await request.json()
    command_type = data.get('command_type')
    args = data.get('args')

    if ff.use_protocol_api_v2():
        hw_mods = await hw.discover_modules()
    else:
        hw_mods = hw.attached_modules.values()

    if len(hw_mods) == 0:
        return web.json_response({"message": "No connected modules"},
                                 status=404)

    matching_mod = next((mod for mod in hw_mods if
                        mod.device_info.get('serial') == requested_serial),
                        None)

    if not matching_mod:
        return web.json_response({"message": "Specified module not found"},
                                 status=404)

    if hasattr(matching_mod, command_type):
        clean_args = args or []
        method = getattr(matching_mod, command_type)
        if asyncio.iscoroutinefunction(method):
            val = await method(*clean_args)
        else:
            val = method(*clean_args)

        return web.json_response(
            {'message': 'Success', 'returnValue': val},
            status=200)
    else:
        return web.json_response(
            {'message': f'Module does not have command: {command_type}'},
            status=400)
716001
def execute(self, *args):
        """"""
        command, kwargs = self.parse(*args)
        return self._commands.execute(command, **kwargs)
231422
def command_info(self, command, *commands):
        """"""
        return self.execute(b'COMMAND', b'INFO', command, *commands,
                            encoding='utf-8')
979894
def serial_number(self, serial_number):
        
        if serial_number is not None and len(serial_number) > 64:
            raise ValueError("Invalid value for `serial_number`, length must be less than or equal to `64`")

        self._serial_number = serial_number
158283
def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_fname=None,
                    mod_loader=None, pkg_name=None):
    """"""
    with _ModifiedArgv0(mod_fname):
        with _TempModule(mod_name) as temp_module:
            mod_globals = temp_module.module.__dict__
            _run_code(code, mod_globals, init_globals,
                      mod_name, mod_fname, mod_loader, pkg_name)
    # Copy the globals of the temporary module, as they
    # may be cleared when the temporary module goes away
    return mod_globals.copy()
113123
def __execute_fromimport(module, modname, import_tuples, verbose=False):
    
    if verbose:
        print('[UTIL_IMPORT] EXECUTING %d FROM IMPORT TUPLES' % (len(import_tuples),))
    from_imports = __get_from_imports(import_tuples)
    for name, fromlist in from_imports:
        full_modname = '.'.join((modname, name))
        tmp = __import__(full_modname, globals(), locals(), fromlist=fromlist, level=0)
        for attrname in fromlist:
            setattr(module, attrname, getattr(tmp, attrname))
    return from_imports
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)
3091
def execute_command(self, *args, **options):
        """"""
        pool = self.connection_pool
        command_name = args[0]
        for i in _xrange(self.execution_attempts):
            connection = pool.get_connection(command_name, **options)
            try:
                connection.send_command(*args)
                res = self.parse_response(connection, command_name, **options)
                pool.release(connection)
                return res
            except ConnectionError:
                pool.purge(connection)
                if i >= self.execution_attempts - 1:
                    raise
1331428
def run_command(self, cmd, history=True, new_prompt=True):
        """"""
        if not cmd:
            cmd = ''
        else:
            if history:
                self.add_to_history(cmd)
        if not self.multithreaded:
            if 'input' not in cmd:
                self.interpreter.stdin_write.write(
                                                to_binary_string(cmd + '\n'))
                self.interpreter.run_line()
                self.refresh.emit()
            else:
                self.write(_('In order to use commands like "raw_input" '
                             'or "input" run Spyder with the multithread '
                             'option (--multithread) from a system terminal'),
                           error=True)
        else:
            self.interpreter.stdin_write.write(to_binary_string(cmd + '\n'))
871573
def execute_command(command):
    """"""

    command = shlex.split(command)
    try:
        process = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    except FileNotFoundError:
        raise RuntimeError("Command not found: {}".format(repr(command)))
    process.wait()
    # TODO: may use another codec to decode
    if process.returncode > 0:
        stderr = process.stderr.read().decode("utf-8")
        raise ValueError("Error executing command: {}".format(repr(stderr)))
    return process.stdout.read().decode("utf-8")
1231105
def module(command, *args):
    """"""

    if 'MODULESHOME' not in os.environ:
        print('payu: warning: No Environment Modules found; skipping {0} call.'
              ''.format(command))
        return

    modulecmd = ('{0}/bin/modulecmd'.format(os.environ['MODULESHOME']))

    cmd = '{0} python {1} {2}'.format(modulecmd, command, ' '.join(args))

    envs, _ = subprocess.Popen(shlex.split(cmd),
                               stdout=subprocess.PIPE).communicate()
    exec(envs)
1348597
def exec_command(attr, cmd):
    
    import subprocess

    p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()

    if p.returncode:
        from rez.exceptions import InvalidPackageError
        raise InvalidPackageError(
            "Error determining package attribute '%s':\n%s" % (attr, err))

    return out.strip(), err.strip()
1349734
def execute_console_command(frame, thread_id, frame_id, line, buffer_output=True):
    
    console_message = ConsoleMessage()

    interpreter = get_interactive_console(thread_id, frame_id, frame, console_message)
    more, output_messages, error_messages = interpreter.push(line, frame, buffer_output)
    console_message.update_more(more)

    for message in output_messages:
        console_message.add_console_message(CONSOLE_OUTPUT, message)

    for message in error_messages:
        console_message.add_console_message(CONSOLE_ERROR, message)

    return console_message
443056
def _run_serial_ops(state):
    '''
    
    '''

    for host in list(state.inventory):
        host_operations = product([host], state.get_op_order())
        with progress_spinner(host_operations) as progress:
            try:
                _run_server_ops(
                    state, host,
                    progress=progress,
                )
            except PyinfraError:
                state.fail_hosts({host})
922133
def _command(self, sock_info, command, slave_ok=False, value=1, check=True,
                 allowable_errors=None, read_preference=ReadPreference.PRIMARY,
                 codec_options=DEFAULT_CODEC_OPTIONS,
                 write_concern=None,
                 parse_write_concern_error=False, session=None, **kwargs):
        """"""
        if isinstance(command, string_type):
            command = SON([(command, value)])

        command.update(kwargs)
        with self.__client._tmp_session(session) as s:
            return sock_info.command(
                self.__name,
                command,
                slave_ok,
                read_preference,
                codec_options,
                check,
                allowable_errors,
                write_concern=write_concern,
                parse_write_concern_error=parse_write_concern_error,
                session=s,
                client=self.__client)
693610
def run(self, conn, tmp, module_name, module_args, inject):
        '''  '''

        # shell and command are the same module
        if module_name == 'shell':
            module_name = 'command'
            module_args += " #USE_SHELL"

        vv("REMOTE_MODULE %s %s" % (module_name, module_args), host=conn.host)
        return self.runner._execute_module(conn, tmp, module_name, module_args, inject=inject)
1344541
def execute_command(self, cmnd, *args, **options):
        ""
        args, options = self.preprocess_command(cmnd, *args, **options)
        return self.client.execute_command(cmnd, *args, **options)