exit loop on keypress in either Shell/Terminal or variable change
-
21-12-2019 - |
Question
So i'm on my Raspberry pi, and i'm wanting to check to see if a sensor has been activated. I'm potentially running off two different things though, one from a shell that i remote into, and the other off a LCD screen with a couple buttons directly connected to the RPi. I think the best way to do this is to run a loop to see if the user press a key (like the enter key or something) OR if the LCD interface has selected to go on. i'd like to run a loop that check if the user has pressed a key or if a variable has changed somewhere denoting the LCD interface has been changed and then move on with my code, but i don't know the best way to do this. Currently, this is what i have:
import thread
import time
import globals #this is where i keep my project wide global variables. it this this is a good way to do it....
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
char = None
def keypress():
global char
char = getch()
thread.start_new_thread(keypress, ())
globals.LCDVar = 0
while True:
if char is not None:
print "Key pressed is " + char
break
if globals.LCDVar == 1
break
time.sleep(.1)
print "Program is running\n"
<Run whatever code next>
This works, but i'm not sure what happens to the thread that's created. Does the thread stay alive after i press a key? I if change the variable instead of pressing a key, won't the thread still be there? I would feel comfortable with this if the event would only happen once or twice, but this keypress/varble check might happen 100s or 1000s of times and i don't want to keep starting new threads over and over again.
Is there a better way to do this?
Thanks for any advice!!
Solution
The thread you created exits when the function called in start_new_thread
returns, so you don't need to worry about it running forever (that's from the official documentation on thread.start_new_thread
).
As far as the "best" way to do this, I think that reversing what is run in a separate thread and what is run in the main line of execution would be helpful. That is, do work in a separate thread and wait for a key press in the main thread. That's traditionally how functionality like this is implemented and it reduces some of the complexity of your loop.