Python multiprocessing atexit errore “Error in atexit._run_exitfuncs”
Domanda
Sto cercando di eseguire una semplice applicazione più processi in Python. Il filo conduttore genera 1 a processi N e attende fino a che tutti fatto elaborazione. I processi di ogni corsa un ciclo infinito, in modo che possano potenzialmente funzionare per sempre senza qualche interruzione di utente, così ho messo in qualche codice per gestire un KeyboardInterrupt:
#!/usr/bin/env python
import sys
import time
from multiprocessing import Process
def main():
# Set up inputs..
# Spawn processes
Proc( 1).start()
Proc( 2).start()
class Proc ( Process ):
def __init__ ( self, procNum):
self.id = procNum
Process.__init__(self)
def run ( self ):
doneWork = False
while True:
try:
# Do work...
time.sleep(1)
sys.stdout.write('.')
if doneWork:
print "PROC#" + str(self.id) + " Done."
break
except KeyboardInterrupt:
print "User aborted."
sys.exit()
# Main Entry
if __name__=="__main__":
main()
Il problema è che quando si usa CTRL-C per uscire, ottengo un errore aggiuntivo, anche se i processi sembrano uscire immediatamente:
......User aborted.
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python26\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python26\lib\multiprocessing\util.py", line 281, in _exit_function
p.join()
File "C:\Python26\lib\multiprocessing\process.py", line 119, in join
res = self._popen.wait(timeout)
File "C:\Python26\lib\multiprocessing\forking.py", line 259, in wait
res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
KeyboardInterrupt
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python26\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python26\lib\multiprocessing\util.py", line 281, in _exit_function
p.join()
File "C:\Python26\lib\multiprocessing\process.py", line 119, in join
res = self._popen.wait(timeout)
File "C:\Python26\lib\multiprocessing\forking.py", line 259, in wait
res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
KeyboardInterrupt
Sono in esecuzione Python 2.6 su Windows. Se c'è un modo migliore per gestire multiprocessing in Python, per favore fatemelo sapere.
Soluzione
piuttosto che solo forzando sys.exit()
, si desidera inviare un segnale al thread per dire loro di smettere. Considerare di usare gestori di segnale e le discussioni in Python.
Si potrebbe farlo modificando il ciclo while True:
essere while keep_processing:
dove keep_processing
è una sorta di variabile globale che viene impostato sul l'eccezione KeyboardInterrupt. Non credo che questa è una buona pratica però.