OK so I want to create an endless loop in Python, the reason is I want to eventually create 4 software pulse with modulated outputs. Because of the nature of PWM is switching in terms of thousands per second I figured I would need 4 threads one for each instance. Now I know I could get some hardware and create hardware PWM outputs, but for testing stuff I want to use software.
to start with I just created the fowling simple snip-it of code. Very simple it creates a single thread and then prints on/off once ever 0.5 seconds.
The issue I found is that it is an endless loop (which is good), but I realised that I cant use Ctrl^c to break out of the loop during testing. To insure that if I need to break out of the code while it is running during testing where would be the best place to put the "try" block, I see that once the main loop exits the ctrl^c is no longer captured.
Thank you
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, pin):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.pin = pin
def run(self):
print "Starting " + self.name
print_time(self.pin)
print "Exiting " + self.name
def print_time(pin):
while True:
try:
on = .5
off = .5
print (pin, "on")
time.sleep(on)
print (pin, "off")
time.sleep(off)
except KeyboardInterrupt:
break
except:
break
# Create new threads
thread1 = myThread(1, "Thread-1", 11)
# Start new Threads
thread1.start()
print "Exiting Main Thread"
pi@UnderTV ~ $ ./threads2.py
Exiting Main Thread
Starting Thread-1
(11, 'on')
(11, 'off')
(11, 'on')
(11, 'off')
(11, 'on')
(11, 'off')
(11, 'on')
(11, 'off')
^X(11, 'on')
^X(11, 'off')
(11, 'on')
^C(11, 'off')
^C(11, 'on')
^C(11, 'off')