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
  • 相关阅读:
    T-Pot平台Honeytrap蜜罐TCP/UDP服务攻击探测及实现自动化邮件告警
    Linux判断文件是否为空,不为空则打印该文件的大小
    Linux好用的工具命令
    T-Pot平台cowrie蜜罐暴力破解探测及实现自动化邮件告警
    python工具
    python文件的基础操作
    python实现合并两个文件并打印输出
    python打开文件的N种姿势
    python工具
    python列表中元素插入位置总结
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/12658471.html
Copyright © 2011-2022 走看看