Execute a command and save the output to a file for inclusion in the
        report.
188134
def get_cmd_output_now(self, exe, suggest_filename=None,
                           root_symlink=False, timeout=300, stderr=True,
                           chroot=True, runat=None, env=None,
                           binary=False, sizelimit=None, pred=None):
        
        if not self.test_predicate(cmd=True, pred=pred):
            self._log_info("skipped cmd output '%s' due to predicate (%s)" %
                           (exe, self.get_predicate(cmd=True, pred=pred)))
            return None

        return self._get_cmd_output_now(exe, timeout=timeout, stderr=stderr,
                                        chroot=chroot, runat=runat,
                                        env=env, binary=binary,
                                        sizelimit=sizelimit)
742024
def output_command(info, image_info, pretty=False):
    ''''''

    sep = pretty and ' \\\n    ' or ' '

    short_options = ''
    options = []

    container = info['Name'][1:]
    conf = info['Config']
    hconf = info['HostConfig']

    options.append("--name={name}".format(name=container))

    if not conf['AttachStdout']:
        short_options += 'd'

    if conf['OpenStdin']:
        short_options += 'i'

    if conf['Tty']:
        short_options += 't'

    if len(short_options) > 0:
        options.append('-' + short_options)

    options.append("-h {hostname}".format(hostname=conf['Hostname']))

    # Volumes
    if 'Binds' in hconf and isinstance(hconf['Binds'], list):
        for volume in hconf['Binds']:
            options.append("-v {volume}".format(volume=volume))

    # PortBindings
    if 'PortBindings' in hconf and isinstance(hconf['PortBindings'], dict):
        for port, hosts in hconf['PortBindings'].items():
            for host in hosts:
                portbinding = ''
                if 'HostIp' in host and host['HostIp']:
                    portbinding += host['HostIp'] + ':'
                if 'HostPort' in host and host['HostPort']:
                    portbinding += host['HostPort'] + ':'
                portbinding += port
                options.append("-p {portbinding}".format(portbinding=portbinding))

    # Devices
    if 'Devices' in hconf and isinstance(hconf['Devices'], list):
        for device in hconf['Devices']:
            options.append("--device={device}".format(device=device))

    # RestartPolicy
    if 'RestartPolicy' in hconf and hconf['RestartPolicy']['Name']:
        policy = hconf['RestartPolicy']['Name']
        if hconf['RestartPolicy']['MaximumRetryCount'] > 0:
            policy += ':' + str(hconf['RestartPolicy']['MaximumRetryCount'])
        options.append("--restart={policy}".format(policy=policy))

    # Privileged
    if hconf['Privileged']:
        options.append('--privileged')

    # DNS
    if 'Dns' in hconf and isinstance(hconf['Dns'], list):
        for dns in hconf['Dns']:
            options.append("-dns={dns}".format(dns=dns))

    # ExposedPorts
    if 'ExposedPorts' in conf and isinstance(conf['ExposedPorts'], dict):
        for port, _ in conf['ExposedPorts'].items():
            if ('ExposedPorts' not in image_info['Config'] or
                    port not in image_info['Config']['ExposedPorts']):
                options.append("--expose={port}".format(port=port))

    # Env
    if isinstance(conf['Env'], list):
        for env in conf['Env']:
            if env not in image_info['Config']['Env']:
                options.append("-e {env}".format(env=pipes.quote(env)))

    # EntryPoint
    if conf['Entrypoint'] != image_info['Config']['Entrypoint']:
        entry = []
        if isinstance(conf['Entrypoint'], list):
            for entry_item in conf['Entrypoint']:
                entry.append(pipes.quote(entry_item))
        elif isinstance(conf['Entrypoint'], str):
            entry.append(pipes.quote(conf['Entrypoint']))
        if len(entry) > 0:
            options.append("--entrypoint={entry}".format(entry=pipes.quote(' '.join(entry))))

    # WorkingDir
    if image_info['Config']['WorkingDir'] != conf['WorkingDir']:
        options.append("-w {dir}".format(dir=pipes.quote(conf['WorkingDir'])))

    # User
    if conf['User'] and image_info['Config']['User'] != conf['User']:
        options.append("-u {user}".format(user=pipes.quote(conf['User'])))

    # Cmd
    cmd = []
    if conf['Cmd'] != image_info['Config']['Cmd']:
        if isinstance(conf['Cmd'], list):
            for cmd_item in conf['Cmd']:
                cmd.append(pipes.quote(cmd_item))
        elif isinstance(conf['Cmd'], str):
            cmd.append(pipes.quote(conf['Cmd']))

    print('# docker-run command for {container}'.format(container=container))
    cmd_str = 'docker run{sep}{options}{sep}{image}'.format(
        options=sep.join(options), sep=sep, image=conf['Image'])

    if len(cmd) > 0:
        cmd_str += ' ' + ' '.join(cmd)

    print(cmd_str)
    print()
672930
def call_out(command):
  
  # start external command process
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

  # get outputs
  out, _ = p.communicate()

  return p.returncode, out.strip()
853813
def execute_cmd(cmd, **kwargs):
    
    yield '$ {}\n'.format(' '.join(cmd))
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.STDOUT

    proc = subprocess.Popen(cmd, **kwargs)

    # Capture output for logging.
    # Each line will be yielded as text.
    # This should behave the same as .readline(), but splits on `\r` OR `\n`,
    # not just `\n`.
    buf = []
    def flush():
        line = b''.join(buf).decode('utf8', 'replace')
        buf[:] = []
        return line

    c_last = ''
    try:
        for c in iter(partial(proc.stdout.read, 1), b''):
            if c_last == b'\r' and buf and c != b'\n':
                yield flush()
            buf.append(c)
            if c == b'\n':
                yield flush()
            c_last = c
    finally:
        ret = proc.wait()
        if ret != 0:
            raise subprocess.CalledProcessError(ret, cmd)
649620
def _execute(self, args, log=True):
        """"""
        if not self._ready:
            self.open_or_create()
        output = ''
        error = ''
        try:
            proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, error = proc.communicate()
            returncode = proc.returncode
            if returncode:
                raise subprocess.CalledProcessError(returncode, proc, (output, error))
            return to_text(output)
        except OSError as e:
            # raise a more meaningful error with the program name
            prog = args[0]
            if prog[0] != os.sep:
                prog = os.path.join(self.path, prog)
            raise OSError('%s: %s' % (prog, six.u(str(e))))
        except subprocess.CalledProcessError as e:
            output, error = e.output
            e.output = output
            raise e
        finally:
            if log:
                try:
                    self._write_to_log(to_text(output))
                    self._write_to_error(to_text(error))
                except NameError:
                    pass
40049
public void execute() {
    try {
      Command command = new Parser().parse();
      try {
        command.execute(new ContextImpl(), execute);
        close();
      } catch (Exception e) {
        throw new RuntimeException(
            "Error while executing command " + command, e);
      } catch (AssertionError e) {
        throw new RuntimeException(
            "Error while executing command " + command, e);
      }
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      writer.close();
      try {
        close();
      } catch (SQLException e) {
        // ignore
      }
    }
  }
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
1142590
def _run_cmd_get_output(cmd):
    
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = process.communicate()
    return out or err
128087
def output_for(cmd, options = {})
      output = StringIO.new
      execute(cmd, options.merge(:outstream => output))
      output.string
    end
902524
def add_cmd_output(self, cmds, suggest_filename=None,
                       root_symlink=None, timeout=300, stderr=True,
                       chroot=True, runat=None, env=None, binary=False,
                       sizelimit=None, pred=None):
        """"""
        if isinstance(cmds, six.string_types):
            cmds = [cmds]
        if len(cmds) > 1 and (suggest_filename or root_symlink):
            self._log_warn("ambiguous filename or symlink for command list")
        if sizelimit is None:
            sizelimit = self.get_option("log_size")
        for cmd in cmds:
            self._add_cmd_output(cmd, suggest_filename=suggest_filename,
                                 root_symlink=root_symlink, timeout=timeout,
                                 stderr=stderr, chroot=chroot, runat=runat,
                                 env=env, binary=binary, sizelimit=sizelimit,
                                 pred=pred)
1220973
def exec_output(cls, command, shell=True, encoding='utf-8'):
        
        proc = Popen(command, shell=shell, stdout=PIPE)
        stdout, _stderr = proc.communicate()
        if proc.returncode == 0:
            return stdout.decode(encoding)

        return ''
1337955
def do_action(self, command, journal = True):
        

        cmd = 0; src = 1; path = 1; data = 2; dst = 2

        if journal is True:
            self.journal.write(json.dumps(command['undo']) + "\n")
            self.journal.flush()

        d = command['do']
        if   d[cmd] == 'copy':   shutil.copy(d[src], d[dst])
        elif d[cmd] == 'move':   shutil.move(d[src], d[dst])
        elif d[cmd] == 'backup': shutil.move(d[src], self.new_backup(d[src]))
        elif d[cmd] == 'write' :
            if callable(d[data]): d[data](d[path])
            else: file_put_contents(d[path], d[data])
146333
def write_output(self, data, args=None, filename=None, label=None):
        """"""
        if args:
            if not args.outlog:
                return 0
        if not filename: filename=args.outlog
        lastpath = ''
        with open(str(filename), 'w') as output_file:
            for entry in data['entries']:
                if args.label:
                    if entry['source_path'] == lastpath:
                        output_file.write(entry['raw_text'] + '\n')
                    elif args.label == 'fname':
                        output_file.write('======== ' + \
                                entry['source_path'].split('/')[-1] + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                    elif args.label == 'fpath':
                        output_file.write('======== ' + \
                                entry['source_path']  + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                else: output_file.write(entry['raw_text'] + '\n')
                lastpath = entry['source_path']
754617
def execute_from_command_line(argv=None):
    """"""
    if sys.stdout.encoding is None:
        print('please set python env PYTHONIOENCODING=UTF-8, example: '
              'export PYTHONIOENCODING=UTF-8, when writing to stdout',
              file=sys.stderr)
        exit(1)

    command = Command(argv)
    command.execute()
211281
private void execute(Command command, CommandLineParser lineParser) {
        ConsoleWrapper wrappedConsole = new ConsoleWrapper(console);
        PrintWriter outputWriter = null;
        try {
            ParsedOptions options = lineParser.parseOptions(command.getOptions());
            outputWriter = OutputRedirection.determineOutputWriter(lineParser.getRedirectionList(), wrappedConsole);
            wrappedConsole.setWriter(outputWriter);
            command.execute(options, wrappedConsole);
        } catch (ConsoleTerminatedException e) {
            throw e;
        } catch (OptionParserException e) {
            wrappedConsole.writeError(e.getMessage());
            command.printHelp(wrappedConsole);
        } catch (Exception e) {
            log.error("Failed to execute command: " + lineParser.getCommandLine(), e);
        } finally {
            if (outputWriter != null) {
                outputWriter.close();
            }
        }
    }
450051
def run
      result = execute(command, args: applicable_files)
      return :pass if result.success?

      result.stdout.split("\n").map(&:strip).reject(&:empty?).
        map { |error| message(error) }
    end
394115
def execute(self, command):
        

        logger.info("running command %s", command)
        cmd = ["podman", "exec", self.get_id()] + command
        output = run_cmd(cmd, return_output=True)

        return output