zoukankan      html  css  js  c++  java
  • stdout,stderr,stdpipe,与Popen.comunicate()理解

    Popen的方法:

    Popen.poll()

      用于检查子进程是否已经结束。设置并返回returncode属性。

    Popen.wait()

      等待子进程结束。设置并返回returncode属性。

    Popen.communicate(input=None)

      与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。

    Popen.send_signal(signal)

      向子进程发送信号。

    Popen.terminate()

      停止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。

    Popen.kill()

      杀死子进程。

    Popen.stdin,Popen.stdout ,Popen.stderr ,官方文档上这么说:

    stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

    Popen.pid

      获取子进程的进程ID。

    Popen.returncode

      获取进程的返回值。如果进程还没有结束,返回None。
    =====================================

    标准输出和标准错误输出分开

    p=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    (stdoutput,erroutput) = p.communicate()

    也可以合并起来,只需要将stderr参数设置为subprocess.STDOUT就可以了,这样子:

    def run_cmd(cmd):
      subp = subprocess.Popen(cmd,
      shell=False,
      stdout=subprocess.PIPE,
      stderr=subprocess.STDOUT)
      stdout, stderr = subp.communicate()
      return stdout.decode("utf-8")
    try:
      stdout = json.loads(stdout)
      status = stdout["retcode"]
      except json.decoder.JSONDecodeError:
      raise ValueError(f"[submit_job]fail, stdout:{stdout}")
      if status != 0:
      raise ValueError(f"[submit_job]fail, status:{status}, stdout:{stdout}")
      return stdout
  • 相关阅读:
    eclipse+myeclipse 使用技巧备忘
    程序员的自我修养
    枚举工具类 EnumUtils
    日期/时间处理工具 DateTimeUtil
    轻松了解Spring中的控制反转和依赖注入(一)
    了解SpringMVC框架及基本工作流程
    HTTP请求行、请求头、请求体详解
    Tomcat项目部署问题记录
    入手IntelliJ IDEA 常用配置
    解决阿里云OSS跨域问题
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/12658471.html
Copyright © 2011-2022 走看看