我有一个
process.py
脚本:
from multiprocessing.connection import Listener
with Listener(('localhost', 6000)) as listener:
with listener.accept() as connection:
message = connection.recv()
# [...]
connection.send(message)
我在线程中启动此脚本(以避免阻塞主线程):
import threading, subprocess
threading.Thread(target=lambda: subprocess.run(['python', 'process.py'])).start()
但有时我想等待(阻塞主线程)直到我的进程启动。
这就是我所做的:
from multiprocessing.connection import Client
nAttempts = 0
while True:
try:
with Client(('localhost', 6000)) as connection:
connection.send(nAttempts)
message = connection.recv()
# [...]
break
except ConnectionRefusedError:
nAttempts += 1
pass
有更好的方法吗?
程序在能够连接之前尝试了约 282 个连接,这会是一个问题吗?
首先修改
process.py
,这样就可以导入你需要的东西了:
from multiprocessing.connection import Listener
def listen(listening_event=None):
with Listener(('localhost', 6000)) as listener:
if listening_event:
listening_event.set() # Signal that we are now listening
with listener.accept() as connection:
message = connection.recv()
# [...]
connection.send(message)
if __name__ == '__main__':
listen()
那么你的主要脚本将是:
import threading
from process import listen
listening_event = threading.Event()
t = Thread(target=listener, args=(listening_event,))
t.start()
listening_event.wait() # Wait for this notification
...
t.join() # Wait for thread to terminate (if it ever does)