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
  • 相关阅读:
    Sql Server数据库使用触发器和sqlbulkcopy大批量数据插入更新
    树莓派安装系统
    ubuntu设置ulimit
    aws申请ec2实例后如何用root用户登录
    python-redis
    Windows Server多用户同时远程登录
    ansible-常用模块
    ansible安装-本机测试
    cmdb实现三种方式
    linux-crond_计划任务
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/12658471.html
Copyright © 2011-2022 走看看