I am currently working with several threads to collect data and save it in a JSON. The loop to collect the data is infinite. I want to be able to end all the threads with CTRL+C. Therefore I created this simple version with two loops. I have tried different things, but can't make it work so far. How can I use "except KeyboardInterrupt" to stop both loops at once? Or is there a better option?
import threading
from time import sleep
number = 0
numberino = 10
def background():
while True:
if number < 10:
global number
number=number+1
print number
sleep(1)
else:
print "10 seconds are over!"
break
def foreground():
while True:
if numberino > -10:
global numberino
numberino=numberino-1
print numberino
sleep(1)
else:
print "20 seconds are over!"
break
b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)
b.start()
f.start()