Invoke a shell command to print cowsay output. Primary replacement for
    os.system calls.
763333
def cowsay_output(message):
    
    command = 'cowsay "%s"' % message
    ret = subprocess.Popen(
        command, shell=True, stdin=subprocess.PIPE,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    output, error = ret.communicate()
    return output, error
925570
def call(exe, *argv):
    
    exes = which(exe)
    if not exes:
        returnValue(None)
    stdout, stderr, value = yield getProcessOutputAndValue(
        exes[0], argv, env=os.environ.copy()
    )
    if value:
        returnValue(None)
    returnValue(stdout.decode('utf-8').rstrip('\n'))
1113109
def call(self, cmd, **kwargs):
        """"""
        if isinstance(cmd, basestring):
            cmd = cmd.split()
        self.log.info('Running %s', cmd)
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, **kwargs)
        out, err = p.communicate()
        if out:
            self.log.info(out)
        if err:
            if p.returncode == 0:
                self.log.info(err)
            else:
                self.log.error(err)
        if p.returncode != 0:
            self.log.error('returncode = %d' % p.returncode)
            raise Exception
        return out, err, p.returncode
590543
def run_command(*cmd, **kwargs):
    ''
    logging.debug('Running: {0} with {1}'.format(cmd, kwargs))
    kwargs['stdout'] = sys.stderr
    subprocess.check_call(cmd, **kwargs)
764451
def do_shell(self, arglist):
        
        proc = subprocess.Popen(
            shlex.split(arglist), stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        print(proc.communicate()[0])
573733
def call_cmd(self, cmd, cwd):
        
        with open(self.cmdfile, 'w') as f:
            f.write(str(cmd))
        stdout = open(self.outfile, 'w')
        stderr = open(self.errfile, 'w')
        logging.info('Calling: ' + ' '.join(cmd))
        process = subprocess.Popen(cmd,
                                   stdout=stdout,
                                   stderr=stderr,
                                   close_fds=True,
                                   cwd=cwd)
        stdout.close()
        stderr.close()

        return process.pid
1018242
def capture_shell(command):
    
    proc = subprocess.Popen(command,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            shell=True)

    return proc.communicate()
118639
def _invoke(self, *params):
		
		cmd = [self.exe] + list(params)
		proc = subprocess.Popen(
			cmd, stdout=subprocess.PIPE,
			stderr=subprocess.PIPE, cwd=self.location, env=self.env)
		stdout, stderr = proc.communicate()
		if not proc.returncode == 0:
			raise RuntimeError(stderr.strip() or stdout.strip())
		return stdout.decode('utf-8')
809465
def _run_command(self, command):
        
        try:
            my_result = call(command, shell=True)
            del my_result
        except CalledProcessError as e:
            LOGGER.exception('Running command failed %s' % command)
            message = (
                'Error while executing the following shell '
                'command: %s\nError message: %s' % (command, str(e)))
            # shameless hack - see https://github.com/AIFDR/inasafe/issues/141
            if sys.platform == 'darwin':  # Mac OS X
                if 'Errno 4' in str(e):
                    # continue as the error seems to be non critical
                    pass
                else:
                    raise Exception(message)
            else:
                raise Exception(message)
563005
def _runcmd(progargs, stdinput=None):
    '''
    
    '''
    stdin = None
    if stdinput is not None:
        assert(isinstance(stdinput, list))
        stdin=PIPE

    err = 0
    output = b''
    log_debug("Calling {} with input {}".format(' '.join(progargs), stdinput))
    try:
        p = Popen(progargs, shell=True, stdin=stdin, 
            stderr=STDOUT, stdout=PIPE, universal_newlines=True)
        if stdinput is not None:
            for cmd in stdinput:
                print(cmd, file=p.stdin)
            p.stdin.close()
        output = p.stdout.read()
        p.stdout.close()
        err = p.wait(timeout=1.0)
    except OSError as e:
        err = e.errno
        log_warn("Error calling {}: {}".format(progargs, e.stderror))
    except Exception as e:
        errstr = str(e)
        log_warn("Error calling {}: {}".format(progargs, errstr))
        err = -1
    log_debug("Result of command (errcode {}): {}".format(err, output))
    return err,output
1142590
def _run_cmd_get_output(cmd):
    
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = process.communicate()
    return out or err
770016
def run(self):
        """"""
        self.logger.debug(f'Running command: {self.cmd}')

        def execute(cmd):
            output = ""
            popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                     universal_newlines=True, shell=True)
            for stdout_line in iter(popen.stdout.readline, ""):
                stdout_line = stdout_line.strip('\n')
                output += stdout_line
                yield stdout_line
            popen.stdout.close()
            return_code = popen.wait()
            if return_code:
                raise subprocess.CalledProcessError(return_code, cmd, output)

        try:
            for out in execute(self.cmd):
                self.logger.info(out)
            return "", 0
        except subprocess.CalledProcessError as e:
            return e.output, e.returncode
115173
def shell(self, command, *args, environment=None):
        
        command += ' ' + ' '.join(args)
        command = command.strip()
        self.debug(self.yellow_style('$ %s' % command))
        env = self.env.copy()
        env.update(environment or {})
        return subprocess.call(command, shell=True, env=env)
620243
def run(self):
    """"""
    if platform.system() == 'Windows':
      # Windows doesn't support file-like objects for select(), so fall back
      # to raw_input().
      response = input(''.join((self._message,
                                os.linesep,
                                PROMPT)))
      self._answered = True
      self._callback(response)
      return

    # First, display the prompt to the console.
    console_output.cli_print(self._message, color=self._color,
                             end=os.linesep, logger=None)
    console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
    sys.stdout.flush()

    # Before reading, clear any lingering buffered terminal input.
    termios.tcflush(sys.stdin, termios.TCIFLUSH)

    line = ''
    while not self._stop_event.is_set():
      inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
      if sys.stdin in inputs:
        new = os.read(sys.stdin.fileno(), 1024)
        if not new:
          # Hit EOF!
          # They hit ^D (to insert EOF). Tell them to hit ^C if they
          # want to actually quit.
          print('Hit ^C (Ctrl+c) to exit.')
          break
        line += new.decode('utf-8')
        if '\n' in line:
          response = line[:line.find('\n')]
          self._answered = True
          self._callback(response)
          return
677666
def shell_cmd(args, cwd=None):
  '''
  '''
  if cwd is None:
    cwd = os.path.abspath('.')
  if not isinstance(args, (list, tuple)):
    args = [args]
  ps = Popen(args, shell=True, cwd=cwd, stdout=PIPE, stderr=PIPE,
             close_fds=True)
  stdout, stderr = ps.communicate()
  if ps.returncode != 0:
    if stderr:
      stderr = stderr.strip()
    raise IOError('Shell command %s failed (exit status %r): %s' %\
      (args, ps.returncode, stderr))
  return stdout.strip()
1263099
def invoke_command (self, cmd, args, **kwargs):
        """"""
        new_kwargs = kwargs.copy ()
        new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name
        new_kwargs['parent'] = self
        new_kwargs['parent_kwargs'] = kwargs
        return cmd.invoke_with_usage (args, **new_kwargs)
1366358
def call(commands, *, print_result=False, raise_exception=False,
         print_commands=False):
    
    if isinstance(commands, str):
        commands = commands.split()

    if not (isinstance(commands, tuple) or
            isinstance(commands, list)):
        raise ValueError("Function 'call' does not accept a 'commands'"
                         "argument of type '{}'".format(type(commands)))

    if raise_exception:
        print_result = False
    try:
        process = subprocess.Popen(commands,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        if print_commands:
            _print_commands(commands)

    except:
        # TODO Why couldn't we just do 'except Exception as output'
        output = traceback.format_exc()
        result = Result(1, stderr=output)
        if print_result and not raise_exception:
            print(output, file=sys.stderr)

    else:
        result = _extract_output(process, print_result, raise_exception)

    if raise_exception and (result.returncode == 1):
        message = "An error occurred in an external process:\n\n{}"
        raise Exception(message.format(result.getStderr()))
    return result