![](/img/trans.png)
[英]Memory usage when reading lines from a piped subprocess stdout in python
[英]closing stdout of piped python subprocess
以下是我在python子進程模塊文檔中可以閱讀的內容:
Replacing shell pipeline
output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1
to receive a SIGPIPE if p2 exits before p1.
我真的不明白為什么在創建p2之后我們必須關閉p1.stdout。 什么時候完全執行p1.stdout.close()? 當p2永遠不會結束時會發生什么? 當p1或p2結束時會發生什么?
在Wikipedia中 , SIGPIPE是在嘗試寫入管道而沒有連接到另一端的進程時發送給進程的信號。
當您首次使用stdout=PIPE
創建p1
,有一個進程連接到管道,這是您的Python進程,您可以使用p1.stdout
讀取輸出。
使用stdin=p1.stdout
創建p2
,現在有兩個進程連接到管道p1.stdout
。
通常,當您在管道中運行進程時,您希望所有進程在任何進程結束時結束。 為了自動執行此操作,您需要關閉p1.stdout
因此p2.stdin
是附加到該管道的唯一進程,這樣如果p2
結束並且p1
將其他數據寫入stdout,它將收到一個SIGPIPE,因為不再有任何進程附在那根煙斗上。
好的我明白了。 p1.stdout從我的python腳本關閉但在p2中保持打開狀態,然后p1和p2一起通信。 除非p2已經關閉,否則p1會收到一個SIGPIPE。 我對么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.