Execute a command in shell or just print it if execute is False
171513
def execute_command(cmd, execute, echo=True):
    """"""
    if execute:
        if echo:
            print("Executing: " + cmd)
        return os.system(cmd)
    else:
        print(cmd)
        return 0
131496
def _execute(cmd):
        """"""
        cmd_parts = shlex.split(cmd)
        if sys.version_info[0] < 3:

            cmd_parts = shlex.split(cmd.encode('ascii'))

        proc = subprocess.Popen(
            cmd_parts,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        out, err = proc.communicate()
        if proc.returncode != 0:

            raise subprocess.CalledProcessError(
                returncode=proc.returncode,
                cmd=cmd,
                output=err,
            )

        return CommandResult(
            code=proc.returncode,
            out=out.decode('utf8'),
            err=err.decode('utf8'),
        )
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)
686346
def run_command(cmd, debug=False):
    
    if debug:
        msg = '  PWD: {}'.format(os.getcwd())
        print_warn(msg)
        msg = '  COMMAND: {}'.format(cmd)
        print_warn(msg)
    cmd()
721801
def run(command, get_output=False, cwd=None):
    
    if cwd is None:
        cwd = GITPATH

    cprint('===')
    cprint('===  Command: ', command)
    cprint('===  CWD:     ', cwd)
    cprint('===')

    if get_output:
        proc = capture_stdout(command, cwd=cwd)
        out = proc.stdout.read().decode()
        print(out, end='')
        check_exit_code(proc.returncode)
        return out
    else:
        proc = sarge_run(command, cwd=cwd)
        check_exit_code(proc.returncode)
917270
def exec(command)
      remote_shell do |shell|
        shell.cd(shell.uri.path)
        shell.exec(command)
      end

      return true
    end
711085
def execute_and_report(command, *args, **kwargs):
    
    logging.info("Execute: %s %s" % (command, " ".join(args)))
    try:
        status, out, err = execute(command, *args, **kwargs)
        if status == 0:
            logging.info(
                "%s Finished successfully. Exit Code: 0.",
                os.path.basename(command),
            )
            return True
        else:
            try:
                logging.error(
                    "%s failed! Exit Code: %s\nOut: %s\nError: %s",
                    os.path.basename(command),
                    status,
                    out,
                    err,
                )
            except Exception as e:
                # This fails when some non ASCII characters are returned
                # from the application
                logging.error(
                    "%s failed [%s]! Exit Code: %s\nOut: %s\nError: %s",
                    e,
                    os.path.basename(command),
                    status,
                    repr(out),
                    repr(err),
                )
            return False
    except Exception:
        logging.exception(
            "%s failed! Exception thrown!", os.path.basename(command)
        )
        return False
603840
def do_shell(self, args):
        """'"""
        if _debug: ConsoleCmd._debug("do_shell %r", args)

        os.system(args)
28829
def perform_command(self):
        
        # if no actual arguments, print help
        if len(self.actual_arguments) < 1:
            return self.print_help(short=True)

        # check if we have a recognized tool switch
        for cls, switches in self.TOOLS:
            if self.has_option(switches):
                arguments = [a for a in sys.argv if a not in switches]
                return cls(invoke=(self.invoke + u" %s" % switches[0])).run(arguments=arguments)

        # check if we have -h, --help, or --version
        if u"-h" in self.actual_arguments:
            return self.print_help(short=True)
        if u"--help" in self.actual_arguments:
            return self.print_help(short=False)
        if u"--version" in self.actual_arguments:
            return self.print_name_version()

        # default to run ExecuteTaskCLI
        return ExecuteTaskCLI(invoke=self.invoke).run(arguments=sys.argv)
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")
308064
def do_command(self):
        """"""
        method = self.args[0]

        raw_args = self.args[1:]
        if '=' in method:
            if raw_args:
                self.parser.error("Please don't mix rTorrent and shell argument styles!")
            method, raw_args = method.split('=', 1)
            raw_args = raw_args.split(',')

        self.execute(self.open(), method, self.cooked(raw_args))
757421
def nice_execute(cmd)
      puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
      stdout, stderr, exit_status = Open3.capture3( cmd )
      unless stdout.empty?
        stdout.each_line do |line|
          print "** [out] #{line}"
          $stdout.flush
        end
      end
      unless stderr.empty?
        stderr.each_line do |line|
          $stderr.print red("** [err] #{line}")
          $stderr.flush
        end
      end
      exit_status
    end
428537
def __execute_cmd(command, host=None,
                  admin_username=None, admin_password=None,
                  module=None):
    '''
    
    '''
    if module:
        # -a takes 'server' or 'switch' to represent all servers
        # or all switches in a chassis.  Allow
        # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'
        if module.startswith('ALL_'):
            modswitch = '-a '\
                        + module[module.index('_') + 1:len(module)].lower()
        else:
            modswitch = '-m {0}'.format(module)
    else:
        modswitch = ''
    if not host:
        # This is a local call
        cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,
                                                              modswitch))
    else:
        cmd = __salt__['cmd.run_all'](
            'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,
                                                         admin_username,
                                                         admin_password,
                                                         command,
                                                         modswitch),
        output_loglevel='quiet')

    if cmd['retcode'] != 0:
        log.warning('racadm returned an exit code of %s', cmd['retcode'])
        return False

    return True
217510
def call(cmd, shell=True, **kwargs):
    "  "

    LOGGER.debug("Cmd: %s" % cmd)
    check_call(cmd, shell=shell, stdout=LOGFILE_HANDLER.stream, **kwargs)
1282567
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
        '''  '''

        if not self.runner.sudo or not sudoable:
            if executable:
                local_cmd = [executable, '-c', cmd]
            else:
                local_cmd = cmd
        else:
            local_cmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)

        vvv("EXEC %s" % (local_cmd), host=self.host)
        p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
                             cwd=self.runner.basedir, executable=executable or None,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if self.runner.sudo and sudoable and self.runner.sudo_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            sudo_output = ''
            while not sudo_output.endswith(prompt):
                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout, p.stderr], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                elif p.stderr in rfd:
                    chunk = p.stderr.read()
                else:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError('timeout waiting for sudo password prompt:\n' + sudo_output)
                if not chunk:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError('sudo output closed while waiting for password prompt:\n' + sudo_output)
                sudo_output += chunk
            p.stdin.write(self.runner.sudo_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL, fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        stdout, stderr = p.communicate()
        return (p.returncode, '', stdout, stderr)
979746
def has_shell_command(self, command):
        
        try:
            output = self.shell(['command', '-v',
                                 command]).decode('utf-8').strip()
            return command in output
        except AdbError:
            # If the command doesn't exist, then 'command -v' can return
            # an exit code > 1.
            return False
1247768
def run_command(cmd, redirect_output=True, check_exit_code=True):
    
    if redirect_output:
        stdout = subprocess.PIPE
    else:
        stdout = None
    proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
    output = proc.communicate()[0]
    if check_exit_code and proc.returncode != 0:
        raise Exception('Command "%s" failed.\n%s' % (' '.join(cmd), output))
    return output