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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM