Parallel While loops - python

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!

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).

Related

Run script at specific time with Python

I want to run the following at 22:00 PM everyday using import datetime.
I'm trying to use a codeRan boolean to trigger it, but I can't get it to work. It's always False:
import datetime
timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374
timeHour = timeNow.strftime("%H") # 22
timeFull = timeNow.strftime("%X") # 10:21:59
timeAMPM = timeNow.strftime("%p") # AM or PM
codeRan = False
if timeHour == "22" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
The code as you wrote it will run the code print(timeHour + " That is correct!") and print 22 That is correct! if your script is run between 10pm-11pm. However, you have not included a loop in your code, so you would need to use some external method to call the script frequently to check whether it is time to run your other script. In linux, you could use crontab to schedule this to run every five minutes, but then if you were planning to do that you could just use crontab to schedule it to run at 10 pm. In windows, TaskScheduler can also be used.
If you want to use python, you really have three options which I can think of (realistically probably way more).
use a while loop (probably the easiest yet least elegant solution because the code would run 24/7
while True:
{your example code here}
Use cron or TaskScheduler
Use subprocess.call to do #2 with Python. Could even check sys.platform to determine whether you are on Linux or Windows.
Check the time, then sleep until it is time to run the code. Again, not great because it means the process must stay alive this entire time.
Additionally, while your method or comparing timeNow.strftime("%H") == '22' does work you also could use time.hour == 22.
I don't know the requirements of your script, but if you simply want to solve the proposed problem, a simple while is missing:
while not codeRan:
if timeHour == "22" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
To prevent checking without a minimum wait, you can insert a sleep at the end of each iteration:
while not codeRan:
if timeHour == "25" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
time.sleep(num_of_seconds)

Code end up in an endless loop. Can't see why

I am working on a simple function to let the user select the language.
But for some reason, I can't see my mistake and the while loop never breaks.
def chooseLanguage():
"""Simple function to let the user choose what language he wants to play in"""
if game["language"] == "en_EN":
import res.languages.en_EN as lang
elif game["language"] == "de_DE":
import res.languages.de_DE as lang
else:
while game["language"] is None:
print ("Hello and welcome! Please select a language.")
print ("1. German / Deutsch")
print ("2. English")
langC = input ("Your choice: ")
if inputValidator(1, langC) == 1:
game["language"] = "de_DE"
break
elif inputValidator(1, langC) == 2:
game["language"] = "en_EN"
break
if game["language"] is None:
chooseLanguage()
else:
pass
Evidently the infinite loop was caused by inputValidator returning a value that was neither equal to 1 or 2. Thus the exit conditions of the loop were never met. And so it continues.

Why if-then statement isn't working?

This is the code that I made when I tried making an if-then statement but, it always defaults to else. Also i just started trying to code from online tutorials today.
print('yes or no?')
if sys.stdin.readline() == 'yes' :
print('Yay')
else :
print('Aww')
This is what happens:
Console:yes or no?
Me:yes
Console:Aww
I've been looking stuff up for half an hour and can't figure out how to fix this please help
sys.stdin.readline() reads a line which ends with '\n' (when you hit "enter").
So you need to remove this '\n' from the captured input using strip().
print('yes or no?')
if sys.stdin.readline().strip() == 'yes' :
print('Yay')
else :
print('Aww')
I tried to explain and solve your specific problem but you could of course use raw_input() or input() (PY3) as mentioned in the other answer.
In python, getting the input of a user's string can be done via input() (or in python 2.7, use raw_input()).
If you include the code:
user_input = raw_input("yes or no?")
This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input.
So, you change your code to be:
user_input = raw_input("yes or no?")
if user_input == "yes":
print("Yay")
else:
print("Aww")
this should have the desired effect.
Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is :
import random
import sys
import os
user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
print('What would you like to add?')
plus1 = float(sys.stdin.readline())
print('Ok so %.1f plus what?' % (float(plus1)))
plus2 = float(sys.stdin.readline())
print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
print('What would you like to subtract?')
minus1 = float(sys.stdin.readline())
print('Ok so %.1f minus what?' % (float(minus1)))
minus2 = float(sys.stdin.readline())
print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
else :
print('That is not one of the above options')
Thanks alot guys!

Text Game Closes after every command - NOTE: I just started out

print "Welcome to the game. In the game you can 'look around' and 'examine things'."
print "There is also some hidden actions.
print "You wake up."
input = raw_input("> ")
haveKey = False
applesExist = True
if input == "look around":
print "You are in a dusty cell. There is a barrel in the corner of the room, an unmade bed,"
print "a cabinet and chest. There is also a cell door."
elif haveKey == False and input == "use door":
print "The door is locked."
elif haveKey == True and input == "use door":
print "You open the door and immediately gets shot with an arrow. You won, kinda."
elif input == "examine barrel":
print "There is apples in the barrel."
elif applesExist == True and input == "eat apple":
print "Mmmmh, that was yummy! But now there are no apples left..."
applesExist = False
elif applesExist == False and input == "eat apple":
print "sury, u et al aples befur!!1111"
elif input == "examine bed":
print "The bed is unmade, and has very dusty sheets. This place really needs a maid."
elif input == "sleep on bed":
print "You lie down and try to sleep, but you can't because of all the bugs crawling on you."
elif input == "examine chest":
print "There is a key in the chest."
elif input == "take key":
haveKey = True
print "You take the key."
elif input == "examine cabinet":
print "The cabinet is made of dark oak wood. There is a endless cup of tea in it."
elif input == "drink tea":
print "You put some tea in your mouth, but immediately spit it out."
print "It seems it has been here for quite some time."
else:
print "Huh, what did you say? Didn't catch that."
No syntax errors, no errors of any kind. Not. One.
The problem is that after I examine, look around and eat apples the
game closes. How do I fix this? With a While loop?
plz halp
You're obviously very beginner, I won't hammer you about how to do the best architecture. Get used to write code a little first.
If you want to repeat an action, that means a loop (here it's called the main game loop). You code currently takes an input, do a lot of checks to do an action on it, do that action and then... reach the end of the file and stops.
If you wan to go back to the input, you need to enclose all the code you want to repeat in a repetitive code structure, i.e. a loop.
Here is a basic pseudo-code of a game main loop.
playing=True:
while playing:
instruction = takeUserInputOfSomeForm();
if instruction == something:
doStuff()
# etc ...
elif instruction == "quit":
playing=False
You need a loop otherwise when the code hits the bottom of the file Python will exit. http://www.tutorialspoint.com/python/python_loops.htm

python -- Crash when trying to deal with unexpected input

So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)

Categories

Resources