在 python3 中优雅地退出多进程
Exit multiprocesses gracefully in python3
我想在 Ctrl+C / SIGINT 或用户输入时正常退出程序。如果可能,终端应该提示类似的东西; "Hit enter to terminate".
Python3.6
要执行的代码
def worker(process):
i = 0
while True:
print('Process %d count %d' % (process, i))
i += 1
def main():
available_num_cores = multiprocessing.cpu_count()
use_num_cores = available_num_cores - 1 if available_num_cores > 1 else 1
print('Using %d cores' % use_num_cores)
pool = multiprocessing.Pool(use_num_cores)
for i in range(0, use_num_cores):
pool.apply_async(worker, args=(i,))
pool.close()
pool.join()
if __name__ == '__main__':
main()
已接受此问题的答案 Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python。不工作,失败并出现错误:
Process SpawnPoolWorker-1:
Process 0 count 1572
Process SpawnPoolWorker-2:
Process 1 count 1472
Process SpawnPoolWorker-3:
Traceback (most recent call last):
如有任何帮助,我们将不胜感激。谢谢!
您需要确保 SIGINT 被子进程忽略。
然后您只需等待用户输入或发出 CTRL+C。
def initializer():
"""Ignore SIGINT in child workers."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
def main():
try:
pool = multiprocessing.Pool(use_num_cores, initializer=initializer)
for i in range(0, use_num_cores):
pool.apply_async(worker, args=(i,))
pool.close()
input("Hit enter to terminate")
except KeyboardInterrupt:
print("CTRL+C")
finally:
pool.terminate()
pool.join()
print("Bye have a great time!")
我想在 Ctrl+C / SIGINT 或用户输入时正常退出程序。如果可能,终端应该提示类似的东西; "Hit enter to terminate".
Python3.6
要执行的代码def worker(process):
i = 0
while True:
print('Process %d count %d' % (process, i))
i += 1
def main():
available_num_cores = multiprocessing.cpu_count()
use_num_cores = available_num_cores - 1 if available_num_cores > 1 else 1
print('Using %d cores' % use_num_cores)
pool = multiprocessing.Pool(use_num_cores)
for i in range(0, use_num_cores):
pool.apply_async(worker, args=(i,))
pool.close()
pool.join()
if __name__ == '__main__':
main()
已接受此问题的答案 Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python。不工作,失败并出现错误:
Process SpawnPoolWorker-1:
Process 0 count 1572
Process SpawnPoolWorker-2:
Process 1 count 1472
Process SpawnPoolWorker-3:
Traceback (most recent call last):
如有任何帮助,我们将不胜感激。谢谢!
您需要确保 SIGINT 被子进程忽略。
然后您只需等待用户输入或发出 CTRL+C。
def initializer():
"""Ignore SIGINT in child workers."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
def main():
try:
pool = multiprocessing.Pool(use_num_cores, initializer=initializer)
for i in range(0, use_num_cores):
pool.apply_async(worker, args=(i,))
pool.close()
input("Hit enter to terminate")
except KeyboardInterrupt:
print("CTRL+C")
finally:
pool.terminate()
pool.join()
print("Bye have a great time!")