r'''
    Helper to exec locally (subprocess) or remotely (paramiko)
183603
def exec_command(command, cwd=None):
    
    '''

    rc = None
    stdout = stderr = None
    if ssh_conn is None:
        ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')}
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=ld_library_path, cwd=cwd)
        stdout, stderr = p.communicate()
        rc = p.returncode
    else:
        # environment= requires paramiko >= 2.1 (fails with 2.0.2)
        final_command = command if cwd is None else 'cd %s && %s %s' % (cwd, 'LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH', command)
        ssh_stdin, ssh_stdout, ssh_stderr = ssh_conn.exec_command(final_command)
        stdout = ''.join(ssh_stdout.readlines())
        stderr = ''.join(ssh_stderr.readlines())
        rc = ssh_stdout.channel.recv_exit_status()

    return rc, stdout, stderr
1325952
def exec_python_rc(*args, **kwargs):
    
    cmdargs, kwargs = __wrap_python(args, kwargs)
    return exec_command_rc(*cmdargs, **kwargs)
440662
def do(cmdline=None, runas=None):
    '''
    
    '''
    path = _pyenv_path(runas)
    cmd_split = cmdline.split()
    quoted_line = ''
    for cmd in cmd_split:
        quoted_line = quoted_line + ' ' + _cmd_quote(cmd)
    result = __salt__['cmd.run_all'](
        'env PATH={0}/shims:$PATH {1}'.format(_cmd_quote(path), quoted_line),
        runas=runas,
        python_shell=True
    )

    if result['retcode'] == 0:
        rehash(runas=runas)
        return result['stdout']
    else:
        return False
1195896
async def execute_process(*cmd, log=None, loop=None):
    '''
    

    '''
    p = await asyncio.create_subprocess_exec(
        *cmd,
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        loop=loop)
    stdout, stderr = await p.communicate()
    if log:
        log.debug("Exec %s -> %d", cmd, p.returncode)
        if stdout:
            log.debug(stdout.decode('utf-8'))
        if stderr:
            log.debug(stderr.decode('utf-8'))
    return p.returncode == 0
939201
def _do_exec(self, cmd, args):
        
        if not args:
            self.stderr.write("execute: empty command\n")
            return
        proc = subprocess.Popen(subprocess.list2cmdline(args),
                shell = True, stdout = self.stdout)
        proc.wait()
95992
def shell_exec(command, **kwargs): # from gitapi.py
  
  proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs)

  out, err = [x.decode("utf-8") for x in  proc.communicate()]

  return {'out': out, 'err': err, 'code': proc.returncode}
587483
def _execute_wk(*args, input=None):
    
    wk_args = (WK_PATH,) + args
    return subprocess.run(wk_args, input=input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
940375
def run_external_subprocess_in_background(command_list, env=None):
    """"""
    if system_os == "Windows":
        DETACHED_PROCESS = 0x00000008
        p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
                stderr=None, close_fds=True, creationflags=DETACHED_PROCESS, env=env)
    else:
        p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
                stderr=None, close_fds=True, env=env)
    return p
695026
def pep517_subprocess_runner(cmd, cwd=None, extra_environ=None):
    # type: (List[AnyStr], Optional[AnyStr], Optional[Mapping[S, S]]) -> None
    """"""
    env = os.environ.copy()
    if extra_environ:
        env.update(extra_environ)

    run(
        cmd,
        cwd=cwd,
        env=env,
        block=True,
        combine_stderr=True,
        return_object=False,
        write_to_stdout=False,
        nospin=True,
    )
458805
def exec_command(self, cmd, tmp_path, sudo_user,sudoable=False, executable='/bin/sh'):
        '''  '''

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-tt", "-q"] + self.common_args + [self.host]

        if not self.runner.sudo or not sudoable:
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)
        else:
            sudocmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            ssh_cmd.append(sudocmd)

        vvv("EXEC %s" % ssh_cmd, host=self.host)
        try:
            # Make sure stdin is a proper (pseudo) pty to avoid: tcgetattr errors
            import pty
            master, slave = pty.openpty()
            p = subprocess.Popen(ssh_cmd, stdin=slave,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = os.fdopen(master, 'w', 0)
        except:
            p = subprocess.Popen(ssh_cmd, stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = p.stdin

        self._send_password()

        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)
            sudo_output = ''
            while not sudo_output.endswith(prompt):
                rfd, wfd, efd = select.select([p.stdout], [],
                                              [p.stdout], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for sudo password prompt')
                    sudo_output += chunk
                else:
                    stdout = p.communicate()
                    raise errors.AnsibleError('ssh connection error waiting for sudo password prompt')
            stdin.write(self.runner.sudo_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        # We can't use p.communicate here because the ControlMaster may have stdout open as well
        stdout = ''
        stderr = ''
        while True:
            rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], 1)
            if p.stdout in rfd:
                dat = os.read(p.stdout.fileno(), 9000)
                stdout += dat
                if dat == '':
                    p.wait()
                    break
            elif p.stderr in rfd:
                dat = os.read(p.stderr.fileno(), 9000)
                stderr += dat
                if dat == '':
                    p.wait()
                    break
            elif p.poll() is not None:
                break
        stdin.close() # close stdin after we read from stdout (see also issue #848)

        if p.returncode != 0 and stderr.find('Bad configuration option: ControlPersist') != -1:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ansible_ssh_args in the config file) before running again')

        return (p.returncode, '', stdout, stderr)
95227
def execute_python_script(self, script):
        
        # Create the local file to copy to remote
        file_handle, filename = tempfile.mkstemp()
        temp_file = os.fdopen(file_handle, "wt")
        temp_file.write(script)
        temp_file.close()

        # Put the file into the remote user directory
        self.put(filename, "python_execute.py")
        command = ["python", "python_execute.py"]

        # Execute the python script on the remote system, clean up, and return the output
        output = self.execute(command, False)
        self.remove("python_execute.py")
        os.unlink(filename)
        return output
1256279
def run(self, command, env={}, path=None,
            uid=None, gid=None, usePTY=0, childFDs=None):
        
        deferred = defer.Deferred()
        processProtocol = _SummaryProcessProtocol(deferred)
        d = defer.maybeDeferred(self.execute, processProtocol, command, env,
                                path, uid, gid, usePTY, childFDs)
        d.addErrback(deferred.errback)
        return deferred
693610
def run(self, conn, tmp, module_name, module_args, inject):
        '''  '''

        # shell and command are the same module
        if module_name == 'shell':
            module_name = 'command'
            module_args += " #USE_SHELL"

        vv("REMOTE_MODULE %s %s" % (module_name, module_args), host=conn.host)
        return self.runner._execute_module(conn, tmp, module_name, module_args, inject=inject)
1093772
def execute(self, processProtocol, command, env={},
                path=None, uid=None, gid=None, usePTY=0, childFDs=None):
        
        raise NotImplementedError()
1337047
def rsync(local_path, remote_path, exclude=None, extra_opts=None):
    """"""
    if not local_path.endswith('/'):
        local_path += '/'
    exclude = exclude or []
    exclude.extend(['*.egg-info', '*.pyc', '.git', '.gitignore',
                    '.gitmodules', '/build/', '/dist/'])
    with hide('running'):
        run("mkdir -p '{}'".format(remote_path))
        return rsync_project(
            remote_path, local_path, delete=True,
            extra_opts='-i --omit-dir-times -FF ' +
                       (extra_opts if extra_opts else ''),
            ssh_opts='-o StrictHostKeyChecking=no',
            exclude=exclude)
999389
def run(cmd):
    """"""
    print("Preparing the following cmd:")
    cmd = prepare_subprocess_cmd(cmd)
    print("Running the following cmd:")
    print('\n'.join(cmd))
    return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr)
629410
def SpawnProcess(popen_args, passwd=None):
  """"""
  if passwd is not None:
    # We send the password via pipe to avoid creating a process with the
    # password as an argument that will get logged on some systems.
    p = subprocess.Popen(popen_args, stdin=subprocess.PIPE)
    p.communicate(input=passwd)
  else:
    p = subprocess.Popen(popen_args)
    p.wait()
  if p.returncode != 0:
    raise ErrorDuringRepacking(" ".join(popen_args))