admin管理员组文章数量:1122832
Ask please why press Ctrl + C ( KeyboardInterrupt) does not work as expected. (the process is not interrupted, continues to work)
from concurrent.futures import ThreadPoolExecutor
def sleeper(n):
while True:
pass
def run():
try:
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(sleeper, list(range(120)))
except KeyboardInterrupt:
exit()
if __name__ == '__main__':
run()
Ask please why press Ctrl + C ( KeyboardInterrupt) does not work as expected. (the process is not interrupted, continues to work)
from concurrent.futures import ThreadPoolExecutor
def sleeper(n):
while True:
pass
def run():
try:
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(sleeper, list(range(120)))
except KeyboardInterrupt:
exit()
if __name__ == '__main__':
run()
Share
Improve this question
edited Nov 25, 2024 at 14:59
Alex Duchnowski
5733 silver badges19 bronze badges
asked Nov 22, 2024 at 17:54
VitaliyVitaliy
154 bronze badges
4
|
1 Answer
Reset to default 1The Keyboard Interrupt
signal is being received, but the program is waiting for all the threads to complete their tasks before actually processing the signal fully. Based on this SO post and this tutorial, I modified your code to create the following program, which will halt as soon as you press Ctrl+C
. It will also terminate even if you don't interrupt it, so you won't have to restart any terminals or run commands to kill individual processes by hand if something goes wrong somehow:
import time
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import Process
def sleeper(n):
print("Sleeper started for", n)
time.sleep(0.25)
return n
def run():
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(sleeper, list(range(500)))
return results
if __name__ == "__main__":
process = Process(target=run)
process.start()
try:
while process.is_alive():
time.sleep(0.1)
except KeyboardInterrupt:
print("Received KeyboardInterrupt")
process.terminate()
本文标签: pythonKeyboardInterrupt doesn39t work as expectedStack Overflow
版权声明:本文标题:python - KeyboardInterrupt doesn't work as expected - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301755a1931287.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
exit
? – Paul M. Commented Nov 23, 2024 at 2:40