Normalize subprocess arguments to handle list commands, string and pipes.
    Piped commands set pipefail and require use of bash to help with debugging
    intermediate errors.
197060
def _normalize_cmd_args(cmd):
    
    if isinstance(cmd, six.string_types):
        # check for standard or anonymous named pipes
        if cmd.find(" | ") > 0 or cmd.find(">(") or cmd.find("<("):
            return "set -o pipefail; " + cmd, True, find_bash()
        else:
            return cmd, True, None
    else:
        return [str(x) for x in cmd], False, None
869749
def normalize_cmd(self, command):
        
        command = command.rstrip()
        command += self.RETURN
        return command
861865
def subprocess_manager(self, exec_args):
        '''  '''
        try:
            sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)
        except OSError:
            raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args))
        out, err = sp.communicate()
        if out:
            print 'standard output of subprocess: %s' % out
        if err:
            raise RuntimeError('%s\npcap_bro had output on stderr: %s' % (exec_args, err))
        if sp.returncode:
            raise RuntimeError('%s\npcap_bro had returncode: %d' % (exec_args, sp.returncode))
1103249
def call(self, args, devnull=False):
        
        if self.debug:
            click.echo(subprocess.list2cmdline(args))
            click.confirm('Continue?', default=True, abort=True)
        try:
            kwargs = {}
            if devnull:
                # Pipe to /dev/null (or equivalent).
                kwargs['stderr'] = subprocess.STDOUT
                kwargs['stdout'] = self.FNULL
            ret_code = subprocess.call(args, **kwargs)
        except subprocess.CalledProcessError:
            return False
        return ret_code
21393
def split_command(cmd, posix=None):
    '''
     
    '''
    if not isinstance(cmd, string_types):
        # cmd is string list
        pass
    else:
        if not PY3:
            # cmd is string
            # The shlex module currently does not support Unicode input (in
            # 2.x)!
            if isinstance(cmd, unicode):
                try:
                    cmd = unicodedata.normalize(
                        'NFKD', cmd).encode('ascii', 'strict')
                except UnicodeEncodeError:
                    raise EasyProcessUnicodeError('unicode command "%s" can not be processed.' % cmd +
                                                  'Use string list instead of string')
                log.debug('unicode is normalized')
        if posix is None:
            posix = 'win' not in sys.platform
        cmd = shlex.split(cmd, posix=posix)
    return cmd
1023467
def _normalize_args(args):
    '''
    
    '''
    if isinstance(args, six.string_types):
        return shlex.split(args)

    if isinstance(args, (tuple, list)):
        return [six.text_type(arg) for arg in args]
    else:
        return [six.text_type(args)]
1167724
def _call(self, command, ignore_errors=None):
        
        if ignore_errors is None:
            ignore_errors = []

        command = self._get_command(command)
        logger.debug("Cmd %s" % command)
        null = open('/dev/null', 'w')
        retcode = subprocess.call(command, stdout=null, stderr=null)
        null.close()

        if retcode in ignore_errors:
            logger.debug(
                "<-- Cmd %s returned %d (ignored)" % (command, retcode))
            return

        if retcode:
            logger.error(
                "<-- Cmd %s returned: %d (error)" % (command, retcode))
            raise subprocess.CalledProcessError(retcode, command)

        logger.debug("<-- Returned %d (good)" % retcode)
        return
137155
def system(*args, **kwargs):
    """"""
    kwargs.setdefault('stdout', subprocess.PIPE)
    proc = subprocess.Popen(args, **kwargs)
    out, _ = proc.communicate()
    if proc.returncode:
        raise SystemExit(proc.returncode)
    return out.decode('utf-8')
874590
def stderr_with_input(cmd, stdin):
    """"""
    handle, gpg_stderr = stderr_handle()
    LOGGER.debug("GPG command %s", ' '.join(cmd))
    try:
        gpg_proc = subprocess.Popen(cmd,  # nosec
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE,
                                    stderr=gpg_stderr)

        output, _err = gpg_proc.communicate(polite_bytes(stdin))

        if handle:
            handle.close()

        return output
    except subprocess.CalledProcessError as exception:
        return gpg_error(exception, 'GPG variable encryption error')
    except OSError as exception:
        raise CryptoritoError("File %s not found" % exception.filename)
499669
def popen_wrapper(args):
    
    try:
        p = Popen(args,
                  shell=False,
                  stdout=PIPE,
                  stderr=PIPE,
                  close_fds=os.name != 'nt',
                  universal_newlines=True)
    except OSError as e:
        raise OSError(
            "Error executing '{:}': '{:}'".format(args[0], e.strerror))
    output, errors = p.communicate()
    return (
        output,
        text_type(errors),
        p.returncode
    )
1103683
def _call(self, command, ignore_errors=None):
        
        if ignore_errors is None:
            ignore_errors = []
        cmd = []
        cmd.extend(self._prefix)
        cmd.extend([self._path, "-iP"])
        cmd.extend(command)
        command = cmd

        logger.debug("Cmd %s" % command)
        null = open('/dev/null', 'w')
        retcode = subprocess.call(command, stdout=null, stderr=null)
        null.close()

        if retcode in ignore_errors:
            logger.debug(
                "<-- Cmd %s returned %d (ignored)" % (command, retcode))
            return

        if retcode:
            logger.error(
                "<-- Cmd %s returned: %d (error)" % (command, retcode))
            raise subprocess.CalledProcessError(retcode, command)

        logger.debug("<-- Returned %d (good)" % retcode)
        return
1329598
def shell(command, *args):
	''''''
	if args:
		command = command.format(*args)

	print LOCALE['shell'].format(command)

	try:
		return subprocess.check_output(command, shell=True)
	except subprocess.CalledProcessError, ex:
		return ex
284834
def handle(self, *args, **options):
        
        if options["sub_command"] == "add":
            self.handle_add(options)
        elif options["sub_command"] == "update":
            self.handle_update(options)
        elif options["sub_command"] == "details":
            self.handle_details(options["username"])
        elif options["sub_command"] == "list":
            self.handle_list(options["all"], options["csv"])
1060488
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False):
		
		
		# Attempt to execute the child process
		proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True)
		(stdout, stderr) = proc.communicate(input)
		
		# If the child process failed and we were asked to raise an exception, do so
		if raiseOnError == True and proc.returncode != 0:
			raise Exception(
				'child process ' + str(command) +
				' failed with exit code ' + str(proc.returncode) +
				'\nstdout: "' + stdout + '"' +
				'\nstderr: "' + stderr + '"'
			)
		
		return CommandOutput(proc.returncode, stdout, stderr)
367249
function s () {
  var args = arrayFrom(arguments)
  var msg = args.shift()
  return args.reduce(replace(/(?:%s|%d)/), '[pipeP] ' + msg)
}
20549
def _run(self, stdout=subprocess.PIPE):
        '''
        
        '''
        assert self._pop is None
        if self._input is not None:
            self._input._run()

        cwd = (self._cwd if self._cwd else os.getcwd()) + '/'

        def glob_or(expr):
            res = [expr]
            if self._expand and ('*' in expr or '?' in expr):
                if expr and expr[0] != '/':
                    expr = cwd + expr
                res = glob.glob(expr)
                if not res:
                    res = [expr]
            return res

        args = [glob_or(arg) for arg in self._args]
        stderr = subprocess.STDOUT if self._err_to_out else None
        assert not self._stdin or self._input is None, "*** ERROR: Stdin must be none outside of head of chain."
        stdin = self._stdin if self._input is None else self._input._pop.stdout
        if stdin is not None and getattr(stdin, 'fileno', None) is None:
            stdin = subprocess.PIPE
        cmd = [self._cmd] + list(itertools.chain.from_iterable(args))
        if self.debug:
            print "*** DEBUG: Run", cmd
        try:
            self._pop = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr,
                                         close_fds=True, cwd=self._cwd, env=self._env)
            if stdin == subprocess.PIPE:
                try:
                    # TODO: Write a non-blocking reader-writer to ship data here
                    self._pop.stdin.write(self._stdin.read())
                except AttributeError:
                    self._pop.stdin.write(self._stdin)
        except OSError:
            print "*** ERROR: %r failed at %r" % (self, self._original_cmd)
            raise
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)