33import multiprocessing
44import os
55import subprocess
6- import sys
76import tempfile
87import textwrap
98import uuid
109from multiprocessing import queues
10+ from multiprocessing .managers import BaseManager
1111from typing import AnyStr
1212
1313import pexpect .fdpexpect
1616
1717from .utils import Meta , remove_asci_color_code , to_bytes , to_str , utcnow_str
1818
19- if sys .platform == 'darwin' :
20- _ctx = multiprocessing .get_context ('fork' )
21- else :
22- _ctx = multiprocessing .get_context ()
19+ _ctx = multiprocessing .get_context ('spawn' )
20+
21+
22+ class MessageQueueManager (BaseManager ):
23+ pass
2324
2425
2526class MessageQueue (queues .Queue ):
@@ -40,7 +41,7 @@ def put(self, obj, **kwargs):
4041 _b = to_bytes (obj )
4142 try :
4243 super ().put (_b , ** kwargs )
43- except : # noqa # queue might be closed
44+ except Exception : # queue might be closed
4445 pass
4546
4647 def write (self , s : AnyStr ):
@@ -53,6 +54,9 @@ def isatty(self):
5354 return True
5455
5556
57+ MessageQueueManager .register ('MessageQueue' , MessageQueue )
58+
59+
5660class PexpectProcess (pexpect .fdpexpect .fdspawn ):
5761 """
5862 Use a temp file to gather multiple inputs into one output, and do `pexpect.expect()` from one place.
@@ -146,16 +150,16 @@ def live_print_call(*args, msg_queue: MessageQueue | None = None, expect_returnc
146150
147151class _PopenRedirectProcess (_ctx .Process ):
148152 def __init__ (self , msg_queue : MessageQueue , logfile : str ):
149- self ._q = msg_queue
150-
151- self .logfile = logfile
152-
153- super ().__init__ (target = self ._forward_io , daemon = True ) # killed by the main process
153+ super ().__init__ (target = self ._forward_io , args = (msg_queue , logfile ), daemon = True )
154154
155- def _forward_io (self ) -> None :
156- with open (self .logfile ) as fr :
155+ @staticmethod
156+ def _forward_io (msg_queue , logfile ) -> None :
157+ with open (logfile ) as fr :
157158 while True :
158- self ._q .put (fr .read ())
159+ try :
160+ msg_queue .put (fr .read ()) # msg_queue may be closed
161+ except Exception :
162+ break
159163
160164
161165class DuplicateStdoutPopen (subprocess .Popen ):
0 commit comments