gpt4 book ai didi

python-3.x - 在 Python 中关闭管道

转载 作者:行者123 更新时间:2023-12-03 16:39:26 24 4
gpt4 key购买 nike

import multiprocessing as mp
import time

"""
1. send item via pipe
2. Receive on the other end by a generator
3. if the pipe is closed on the sending side, retrieve
all item left and then quit.
"""

def foo(conn):
for i in range(7):
time.sleep(.3)
conn.send(i)
conn.close()

def bar(conn):
while True:
try:
yield conn.recv()
except EOFError:
break


if __name__ == '__main__':
"""Choose which start method is used"""
recv_conn, send_conn = mp.Pipe(False)
p = mp.Process(target = foo, args = (send_conn,)) # f can only send msg.
p.start()
# send_conn.close()
for i in bar(recv_conn):
print(i)

我在 Ubuntu 14.04 上使用 Python 3.4.1,但代码不起作用。在程序结束时,没有 EOFError,它应该终止代码,尽管管道已经关闭。在函数内关闭管道不会关闭管道。为什么会这样?

最佳答案

取消注释您的 send_conn.close() 线。您应该关闭不需要它们的进程中的管端。问题在于,一旦您启动子进程,内核就会跟踪对管道发送连接的两个打开引用:一个在父进程中,一个在您的子进程中。

发送连接对象仅在您的子进程中关闭,而在父进程中保持打开状态,因此您的 conn.recv() 调用不会引发 EOFError。管道仍然打开。

This answer可能对你也有用。

如果您取消注释 ,我验证了此代码在 Python 2.7.6 中有效send_conn.close() 称呼。

关于python-3.x - 在 Python 中关闭管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com