Reputation: 3144
I'm certain this is really easy, but I can't find a question about it.
I have a bunch of processes running in a pool; when ctrl+c
is pressed, I want the program to stop and exit cleanly without spamming the screen with "None" for each process closed.
Given the following test code:
#! /usr/bin/env python3
import multiprocessing
import signal
def graceful_close(blah, blah2):
exit()
signal.signal(signal.SIGINT, graceful_close)
def wait():
while True:
pass
try:
pool = multiprocessing.Pool(20)
for i in range(1, 20):
pool.apply_async(wait)
while True:
pass
except KeyboardInterrupt:
exit()
How do I prevent the output:
[-2019-09-15 21:56:06 ~/git/locane $> ./test_mp_exit_spam.py
^CNone
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
[-2019-09-15 21:56:11 ~/git/locane $>
What is even causing it?
Upvotes: 0
Views: 95
Reputation: 6600
Please use sys.exit
instead of exit
.
exit is a helper for the interactive shell - sys.exit is intended for use in programs.
And since you are already handling SIGNINT
, not sure why the need to handle KeyboardInterrupt
explicitly
import sys
import multiprocessing
import signal
def graceful_close(blah, blah2):
sys.exit()
signal.signal(signal.SIGINT, graceful_close)
def wait():
while True:
pass
pool = multiprocessing.Pool(20)
for i in range(1, 20):
pool.apply_async(wait)
while True:
pass
Upvotes: 1