Reputation: 47
I am writing a Python program, and I want to run two while loops at the same time. I am pretty new to Python, so this could be a elementary mistake/misconception. The project is having a Raspberry Pi monitor a sump pump to make sure that it is working, and if not, send an email to the specified recipients. One loop is going to interact with the user, and respond to commands send to it in real time through SSH.
while running is True:
user_input = raw_input("What would you like to do? \n").lower()
if user_input == "tell me a story":
story()
elif user_input == "what is your name":
print "Lancelot"
elif user_input == "what is your quest":
print "To seek the Holy Grail"
elif user_input == "what is your favorite color":
print "Blue"
elif user_input == "status":
if floatSwitch == True:
print "The switch is up"
else:
print "The switch is down"
elif user_input == "history":
print log.readline(-2)
print log.readline(-1) + "\n"
elif user_input == "exit" or "stop":
break
else:
print "I do not recognize that command. Please try agian."
print "Have a nice day!"
The other loop will be monitoring all of the hardware and to send the email if something goes wrong.
if floatSwitch is True:
#Write the time and what happened to the file
log.write(str(now) + "Float switch turned on")
timeLastOn = now
#Wait until switch is turned off
while floatSwitch:
startTime = time.time()
if floatSwitch is False:
log.write(str(now) + "Float switch turned off")
timeLastOff = now
break
#if elapsedTime > 3 min (in the form of 180 seconds)
elif elapsedTime() > 180:
log.write(str(now) + " Sump Pump has been deemed broaken")
sendEmail("The sump pump is now broken.")
break
Both of these functions are critical, and I want them to run in parallel, so how do I get them to run like that? Thanks for everyone's help!
Upvotes: 2
Views: 8916
Reputation: 11060
Stuff running in parallel? Try using threading - see for example this module in the standard library, or the multiprocessing module.
You will need to create a thread for each of the while loops.
This post has some good examples of how to use threads.
On some other notes, I can't help noticing you use if variable is True:
instead of if variable:
and if variable is False:
instead of if not variable:
, the alternatives given being more normal and Pythonic.
When you do elif user_input == "exit" or "stop":
this will always be true because it is actually testing if (use_input == "exit") or ("stop")
. "stop"
is a non-empty string, so it will always evaluate to True
in this context. What you actually want is elif user_input == "exit" or user_input == "stop":
or even elif user_input in ("exit", "stop"):
.
Finally when you do log.write(str(now) + "Float switch turned off")
it would probably better to do string formatting. You could do log.write("{}Float switch turned off".format(now))
, or use %
(I don't know how to do that since I only used Python 2.x for a few weeks before moving to 3.x, where %
has been deprecated).
Upvotes: 1