Run an apt command with optional retries.

    :param: cmd: str: The apt command to run.
    :param: fatal: bool: Whether the command's output should be checked and
        retried.
977939
def _run_apt_command(cmd, fatal=False):
    
    # Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.
    cmd_env = {
        'DEBIAN_FRONTEND': os.environ.get('DEBIAN_FRONTEND', 'noninteractive')}

    if fatal:
        _run_with_retries(
            cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
            retry_message="Couldn't acquire DPKG lock")
    else:
        env = os.environ.copy()
        env.update(cmd_env)
        subprocess.call(cmd, env=env)
1087980
def _run_cmd(cmds):
    """"""
    if not isinstance(cmds, str):
        cmds = "".join(cmds)
    print("Execute \"%s\"" % cmds)
    try:
        subprocess.check_call(cmds, shell=True)
    except subprocess.CalledProcessError as err:
        print(err)
        raise err
262075
def execute(self, cmd, cwd):
        
        self.output = ""
        env = os.environ.copy()
        env.update(self.env)
        if six.PY2:  # nocv
            # Ugly hack because python 2.7.
            if self._stdout == self.DEVNULL:
                self._stdout = open(os.devnull, 'w+b')
            if self._stderr == self.DEVNULL:
                self._stderr = open(os.devnull, 'w+b')
        proc = subprocess.Popen(
            cmd, stdout=self._stdout, stderr=self._stderr,
            bufsize=0, universal_newlines=True,
            cwd=cwd, env=env,
            close_fds=ON_POSIX
        )
        for line in self._unbuffered(proc):
            self.line_handler(line)
        return_code = proc.poll()
        if return_code:
            logger.error(self.output)
            raise subprocess.CalledProcessError(
                return_code, cmd, output=str(self.output)
            )
        return self.output
1201310
def _cmd(self, *nargs):
        """"""
        cmd_str = ' '.join(map(quote, nargs))

        if self.package.config.debug("package_release"):
            print_debug("Running command: %s" % cmd_str)

        p = popen(nargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                  cwd=self.pkg_root)
        out, err = p.communicate()

        if p.returncode:
            print_debug("command stdout:")
            print_debug(out)
            print_debug("command stderr:")
            print_debug(err)
            raise ReleaseVCSError("command failed: %s\n%s" % (cmd_str, err))
        out = out.strip()
        if out:
            return [x.rstrip() for x in out.split('\n')]
        else:
            return []
383379
def _run_command(self, cmdline):
        """"""
        try:
            if self.verbose:
                print(cmdline)
            subprocess.check_call(cmdline, shell=True)
        except subprocess.CalledProcessError:
            print('when running: ', cmdline)
            raise
112620
def execute_command(self, command):
        

        self.runner.info_log("Executing command: %s" % command)

        process = Popen(
                command,
                stdout=open(os.devnull, 'w'),
                stderr=open('runner.log', 'a'),
        )

        return process
829958
def runRemoteCommand(self, cmd, args, abandonOnFailure=True,
                         evaluateCommand=lambda cmd: cmd.didFail()):
        """"""
        cmd = remotecommand.RemoteCommand(cmd, args)
        if hasattr(self, "rc_log"):
            cmd.useLog(self.rc_log, False)
        d = self.runCommand(cmd)

        def commandComplete(cmd):
            if abandonOnFailure and cmd.didFail():
                raise buildstep.BuildStepFailed()
            return evaluateCommand(cmd)

        d.addCallback(lambda res: commandComplete(cmd))
        return d
1367306
def _run_cli_process(cmd, shell=True):
        
        from subprocess import Popen, PIPE

        p = Popen(cmd, shell=shell, stdout=PIPE, stderr=PIPE)
        _stdout, _stderr = p.communicate()
        return _stdout, _stderr, p.returncode
834598
def _cmd(binary, *args):
    '''
    
    '''
    binary = salt.utils.path.which(binary)
    if not binary:
        raise CommandNotFoundError('{0}: command not found'.format(binary))
    cmd = [binary] + list(args)
    return __salt__['cmd.run_stdout']([binary] + list(args),
                                      python_shell=False)
81634
def call_command(self, cmdname, **kw):
        """"""
        for dirname in INSTALL_DIRECTORY_ATTRS:
            kw.setdefault(dirname, self.bdist_dir)
        kw.setdefault('skip_build', self.skip_build)
        kw.setdefault('dry_run', self.dry_run)
        cmd = self.reinitialize_command(cmdname, **kw)
        self.run_command(cmdname)
        return cmd
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
59566
def _execute_cmd(plugin, args='', run_type='cmd.retcode'):
    '''
    
    '''
    data = {}

    all_plugins = list_plugins()
    if plugin in all_plugins:
        data = __salt__[run_type](
                '{0}{1} {2}'.format(PLUGINDIR, plugin, args),
                python_shell=False)

    return data
545995
def run(cmds, **kwargs):
    
    proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT,
                    close_fds=sys.platform != 'win32')
    for line in proc.stdout:
        print(line[:-1].decode())
    retcode = proc.wait()
    if retcode:
        raise sp.CalledProcessError(retcode, cmds)
311826
def run_cmd(command, verbose=True, shell='/bin/bash'):
    """"""
    process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)
    output = process.stdout.read().decode().strip().split('\n')
    if verbose:
        # return full output including empty lines
        return output
    return [line for line in output if line.strip()]
1140647
def _exec(cmd):
        
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

        # pylint: disable=unexpected-keyword-arg
        (stdout, stderr) = process.communicate(timeout=defaults.DEFAULT_VCS_TIMEOUT)

        return process.returncode, stdout.decode(), stderr.decode()
281991
def cmd_ok(cmd):
     
    try:
        sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
    except sp.CalledProcessError:
        # bwa gives return code of 1 with no argument
        pass
    except:
        sys.stderr.write("{} not found, skipping\n".format(cmd))
        return False
    return True
1201073
def _do_run(cmd, checks, log_stdout=False):
    
    cmd, shell_arg, executable_arg = _normalize_cmd_args(cmd)
    s = subprocess.Popen(cmd, shell=shell_arg, executable=executable_arg,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT, close_fds=True)
    debug_stdout = collections.deque(maxlen=100)
    while 1:
        line = s.stdout.readline()
        if line:
            debug_stdout.append(line)
            if log_stdout:
                logger.debug(line.rstrip())
            else:
                logger.debug(line.rstrip())
        exitcode = s.poll()
        if exitcode is not None:
            for line in s.stdout:
                debug_stdout.append(line)
            if exitcode is not None and exitcode != 0:
                error_msg = " ".join(cmd) if not isinstance(cmd, basestring) else cmd
                error_msg += "\n"
                error_msg += "".join(debug_stdout)
                s.communicate()
                s.stdout.close()
                raise subprocess.CalledProcessError(exitcode, error_msg)
            else:
                break
    s.communicate()
    s.stdout.close()
    # Check for problems not identified by shell return codes
    if checks:
        for check in checks:
            if not check():
                raise IOError("External command failed")