Python: Perform ations repeatedly over a time interval, as long as a condition is true
So I'm trying to do this (access a file on a website, read its contents and perform actions until the content says to exit. The precondition being it has to wait x seconds before accessing the website again; to recheck the contents):
perform = True while(perform): data = urllib.urlopen('someurl') data = data.read() if(data == '0'): dosomething() elif(data == '1'): #1 signifies to exit the loop perform = False else: time.sleep(10)
However this never seems to work. 'Someurl' always has a value. Some Google says that it's something to do with the sleep function. Please help!
Answers
this:
import time while True: print "fetching" time.sleep(10)
is the minimal test case and as this always works it can't be a problem with the time.sleep function
1) Have you tried actually checking what data you get back from reading the URL? Like, printing it out or something?
2) If the data does actually match '0' or '1', then you don't get to the else case, so the sleep() doesn't happen. This is bad because it means you try to read the data again immediately. It probably won't have changed, and web servers usually don't like you very much when you ask them for the same URL over and over without pausing (they think you are trying to hack them). Solution: don't put the sleep() call in an else case; just leave it at the same level as the original if. You don't need an else to have valid code.