當前位置: 首頁>>代碼示例>>Python>>正文


Python subprocess32.Popen方法代碼示例

本文整理匯總了Python中subprocess32.Popen方法的典型用法代碼示例。如果您正苦於以下問題:Python subprocess32.Popen方法的具體用法?Python subprocess32.Popen怎麽用?Python subprocess32.Popen使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在subprocess32的用法示例。


在下文中一共展示了subprocess32.Popen方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: exec_command

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def exec_command(cmd, args, cwd, timeout=None):
    """
    Executes shell command inside @repo_path
    returns exec code
    """
    pipe = None
    try:
        env = os.environ
        env["PATH"] = env["NDK_TOOLCHAIN"] + "/bin:" + env["PATH"]
        pipe = Popen(args, stdin=PIPE, stdout=PIPE, cwd=cwd, env=env)
        stdout, error = pipe.communicate(timeout=timeout) if (timeout and timeout > 0) else pipe.communicate()
        logger.debug("stdout: %s", stdout)
        return pipe.returncode

    except TimeoutExpired as te:
        pipe.terminate()
        logger.error("%s timed out: %s", cmd, str(te))
        return 0

    except Exception as e:
        logger.error("%s subprocess failed: %s", cmd, str(e))
        return -1 
開發者ID:osssanitizer,項目名稱:osspolice,代碼行數:24,代碼來源:signature.py

示例2: run_cmd

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def run_cmd(cmd):
    c = cmd[:-1]
    timeout = cmd[-1]
    display("Executing command: %s" % " ".join(c))

    current_time = time.time()

    if timeout:
        process = Popen(c)
        while time.time() < current_time + timeout and process.poll() is None:
            time.sleep(5)
        if process.poll() is None:

            display_error(
                "Timeout of %s reached. Aborting thread for command: %s"
                % (timeout, " ".join(c))
            )
            process.terminate()

    else:
        Popen(c).wait()

    return cmd 
開發者ID:depthsecurity,項目名稱:armory,代碼行數:25,代碼來源:ModuleTemplate.py

示例3: open_process

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def open_process(cls, cmd, **kwargs):
    """Opens a process object via subprocess.Popen().

    :param string|list cmd: A list or string representing the command to run.
    :param **kwargs: Additional kwargs to pass through to subprocess.Popen.
    :return: A `subprocess.Popen` object.
    :raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
    """
    assert len(cmd) > 0, 'cannot execute an empty command!'

    try:
      return subprocess.Popen(cmd, **kwargs)
    except (IOError, OSError) as e:
      if e.errno == errno.ENOENT:
        raise cls.ExecutableNotFound(cmd, e)
      else:
        raise cls.ExecutionError(repr(e), cmd, e) 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:19,代碼來源:executor.py

示例4: execute

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def execute(cls, cmd, stdin_payload=None, **kwargs):
    """Execute a command via subprocess.Popen and returns the stdio.

    :param string|list cmd: A list or string representing the command to run.
    :param string stdin_payload: A string representing the stdin payload, if any, to send.
    :param **kwargs: Additional kwargs to pass through to subprocess.Popen.
    :return: A tuple of strings representing (stdout, stderr), pre-decoded for utf-8.
    :raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
             `Executor.NonZeroExit` when the execution fails with a non-zero exit code.
    """
    process = cls.open_process(cmd=cmd,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               **kwargs)
    stdout_raw, stderr_raw = process.communicate(input=stdin_payload)
    # N.B. In cases where `stdout` or `stderr` is passed as parameters, these can be None.
    stdout = stdout_raw.decode('utf-8') if stdout_raw is not None else stdout_raw
    stderr = stderr_raw.decode('utf-8') if stderr_raw is not None else stderr_raw

    if process.returncode != 0:
      raise cls.NonZeroExit(cmd, process.returncode, stdout, stderr)

    return stdout, stderr 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:26,代碼來源:executor.py

示例5: command

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def command(cmd, *arguments, **options):

    close_fds = options.get('close_fds', True)
    cwd = options.get('cwd', None)
    shell = options.get('shell', False)
    env = options.get('env', None)
    if env is not None:
        env = dict(os.environ, **env)
    stdin = options.get('stdin', None)

    subproc = subprocess32.Popen([cmd] + list(arguments),
                                 close_fds=close_fds,
                                 shell=shell,
                                 cwd=cwd,
                                 env=env,
                                 stdin=subprocess32.PIPE,
                                 stdout=subprocess32.PIPE,
                                 stderr=subprocess32.PIPE, )

    out, err = subproc.communicate(input=stdin)

    subproc.wait()

    return (subproc.returncode, out, err) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:26,代碼來源:proc.py

示例6: subproc

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def subproc(script, cwd=None):

    subproc = subprocess32.Popen(['sh'],
                               close_fds=True,
                               cwd=cwd,
                               stdin=subprocess32.PIPE,
                               stdout=subprocess32.PIPE,
                               stderr=subprocess32.PIPE)

    out, err = subproc.communicate(script)

    subproc.wait()

    if subproc.returncode != 0:
        print out
        print err

    return (subproc.returncode, out, err) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:20,代碼來源:test_logutil.py

示例7: start_worker

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def start_worker(node_ip_address, worker_path, scheduler_address, objstore_address=None, cleanup=True):
  """This method starts a worker process.

  Args:
    node_ip_address (str): The IP address of the node that the worker runs on.
    worker_path (str): The path of the source code which the worker process will
      run.
    scheduler_address (str): The ip address and port of the scheduler to connect
      to.
    objstore_address (Optional[str]): The ip address and port of the object
      store to connect to.
    cleanup (Optional[bool]): True if using Ray in local mode. If cleanup is
      true, then this process will be killed by serices.cleanup() when the
      Python process that imported services exits. This is True by default.
  """
  command = ["python",
             worker_path,
             "--node-ip-address=" + node_ip_address,
             "--scheduler-address=" + scheduler_address]
  if objstore_address is not None:
    command.append("--objstore-address=" + objstore_address)
  p = subprocess.Popen(command)
  if cleanup:
    all_processes.append(p) 
開發者ID:ray-project,項目名稱:ray-legacy,代碼行數:26,代碼來源:services.py

示例8: ensure_terminated

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def ensure_terminated(self, status=""):
        if self._popen:
            try:
                os.kill(self._popen.pid, signal.SIGINT)
            except OSError:
                print "Process does not exist"
                return
            time.sleep(0.5)
            if self._popen:
                self._popen.poll()

                if self._popen.returncode is None:
                    self._popen.terminate()
                    time.sleep(0.2)
                    self._popen.poll()

                while self._popen.returncode is None:
                    time.sleep(1)
                    if status:
                        print(status)
                    self._popen.poll()
        else:
            print "ERROR Popen is NONE" 
開發者ID:AMZ-Driverless,項目名稱:fssim,代碼行數:25,代碼來源:shell.py

示例9: open_process

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def open_process(command, cwd=None, shell=True, _popen_lock=threading.Lock()):
    kwargs = {
        "shell": shell,
        "stdout": subprocess.PIPE,
        "stderr": subprocess.STDOUT,
        "stdin": subprocess.PIPE,
        "bufsize": 1,  # Line buffered
        "universal_newlines": True,
    }

    if cwd is not None:
        kwargs["cwd"] = cwd

    # Prevent signal propagation from parent process
    try:
        # Windows
        kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
    except AttributeError:
        # Unix
        kwargs["preexec_fn"] = os.setpgrp

    with _popen_lock:  # Work around Python 2 Popen race condition
        return subprocess.Popen(command, **kwargs) 
開發者ID:niklasf,項目名稱:fishnet,代碼行數:25,代碼來源:fishnet.py

示例10: xvfb_supports_listen

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def xvfb_supports_listen():
    """Determine whether the '-listen' option is supported by Xvfb."""
    p = subprocess.Popen(
        ['Xvfb', '-listen', 'TCP', '-__sentinel_parameter__'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    p.wait()
    _, stderr = p.communicate()

    match = re.search(
        br'^Unrecognized option: (?P<option>.*)$',
        stderr,
        flags=re.MULTILINE,
    ).groupdict()
    unrecognized_option = match['option']
    return unrecognized_option != b'-listen' 
開發者ID:pytest-dev,項目名稱:pytest-services,代碼行數:19,代碼來源:xvfb.py

示例11: check_output

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def check_output(*popenargs, **kwargs):
    """Run command with arguments and return its output (both stdout and stderr) as a byte string.

    If the exit code was non-zero it raises a CalledProcessWithOutputError.
    """
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    if 'stderr' in kwargs:
        raise ValueError('stderr argument not allowed, it will be overridden.')

    process = subprocess.Popen(
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        *popenargs, **kwargs)
    output, err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessWithOutputError(retcode, cmd, output, err)

    return output, err 
開發者ID:pytest-dev,項目名稱:pytest-services,代碼行數:26,代碼來源:process.py

示例12: run_in_subprocess

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def run_in_subprocess(cmd, check_output=False, **kwargs):
    """
    Execute command using default subprocess configuration.

    Parameters
    ----------
    cmd : string
        Command to be executed in subprocess.
    kwargs : keywords
        Options to pass to subprocess.Popen.

    Returns
    -------
    proc : Popen subprocess
        Subprocess used to run command.
    """

    logger.debug('Executing command: {0}'.format(cmd))
    config = DEFAULT_SUBPROCESS_CONFIG.copy()
    config.update(kwargs)
    if not check_output:
        if omniduct_config.logging_level < 20:
            config['stdout'] = None
            config['stderr'] = None
        else:
            config['stdout'] = open(os.devnull, 'w')
            config['stderr'] = open(os.devnull, 'w')
    timeout = config.pop('timeout', None)

    process = subprocess.Popen(cmd, **config)
    try:
        stdout, stderr = process.communicate(None, timeout=timeout)
    except subprocess.TimeoutExpired:
        os.killpg(os.getpgid(process.pid), signal.SIGINT)  # send signal to the process group, recursively killing all children
        output, unused_err = process.communicate()
        raise subprocess.TimeoutExpired(process.args, timeout, output=output)
    return SubprocessResults(returncode=process.returncode, stdout=stdout or b'', stderr=stderr or b'') 
開發者ID:airbnb,項目名稱:omniduct,代碼行數:39,代碼來源:processes.py

示例13: run_cmd_noout

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def run_cmd_noout(cmd_data):
    cmd = cmd_data[0]
    output = cmd_data[1]
    c = cmd[:-1]
    timeout = cmd[-1]
    display("Executing command: %s" % " ".join(c))

    current_time = time.time()
    f = open(output, 'w')
    if timeout:
        
        process = Popen(c, stdout=f, stderr=STDOUT)
        while time.time() < current_time + timeout and process.poll() is None:
            time.sleep(5)
        if process.poll() is None:

            display_error(
                "Timeout of %s reached. Aborting thread for command: %s"
                % (timeout, " ".join(c))
            )
            process.terminate()

    else:
        Popen(c, stdout=f, stderr=STDOUT).wait()
    f.close()
    return cmd_data 
開發者ID:depthsecurity,項目名稱:armory,代碼行數:28,代碼來源:ModuleTemplate.py

示例14: run_proc_with_quit

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def run_proc_with_quit(proc_id, quit_dict, args, logfile=None, append=False, env=None, cwd=None):
    if logfile is None:
        logfile = os.devnull

    mode = 'ab' if append else 'wb'
    with open(logfile, mode) as logf:
        if proc_id in quit_dict:
            return None
        proc = subprocess.Popen(args, stdout=logf, stderr=subprocess.STDOUT,
                                env=env, cwd=cwd)
        retcode = None
        num_kill = 0
        timeout = 0.05
        while retcode is None and num_kill <= 2:
            try:
                retcode = proc.wait(timeout=timeout)
            except subprocess.TimeoutExpired:
                if proc_id in quit_dict:
                    if num_kill == 0:
                        proc.terminate()
                        timeout = quit_dict[proc_id]
                    elif num_kill == 1:
                        proc.kill()
                    num_kill += 1

        return proc.returncode 
開發者ID:ucb-art,項目名稱:BAG_framework,代碼行數:28,代碼來源:process.py

示例15: test_stdin_stdout

# 需要導入模塊: import subprocess32 [as 別名]
# 或者: from subprocess32 import Popen [as 別名]
def test_stdin_stdout(self):
        proc = subprocess32.Popen(
            (sys.executable, '-m', 'pykit.p3json.tool'),
            stdin=subprocess32.PIPE, stdout=subprocess32.PIPE)
        out, err = proc.communicate(self.data.encode())
        self._assert_expected(out, linemode=True)
        self.assertEqual(err, None) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:9,代碼來源:test_tool.py


注:本文中的subprocess32.Popen方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。