0
print(7)
sleep(10)
print(8)

when i typed this in Spyder's command line, I expected 7 to be printed, then after 10 seconds 8, would be printed, however, what happened was that both 7 and 8 are printed after a 10 second pause, why is this the case?

The reason I need this function is that I want Python to keep on searching for a file in a directory until it eventually appears.

done = os.path.exists ("done.txt")
while not done:
    sleep(10)
    done = os.path.exists ("done.txt")

will this work?

EDIT: corrected exist as exists.

lospejos
  • 1,976
  • 3
  • 19
  • 35
Lost1
  • 990
  • 1
  • 14
  • 34
  • 4
    Possible duplicate of [Python3 sleep() problem](http://stackoverflow.com/questions/4456581/python3-sleep-problem) – Blorgbeard Dec 29 '16 at 19:24
  • For your problem wouldn't `done` be initialized once in the beginning? `sleep(10)` will never occur then. Maybe you should check for `os.path.exist()` as the `while` condition. Like `while os.path.exists('/your/path/file.txt')`? –  Dec 29 '16 at 19:28
  • It should be `os.path.exists` not `os.path.exist`. Other than that, this should work fine. – Joshua Grigonis Dec 29 '16 at 19:29

1 Answers1

2

First: It should be os.path.exists not os.path.exist.

Other than that, this should work fine.

Second: I think kiran.konduru misunderstood the question, but you could certainly simplify this and remove the need for the done variable:

while not os.path.exists("done.txt"):
    sleep(10)

Finally: The time.sleep() function is getting buffered in the Spyder command line, see here. If you use sys.stdout.write() and sys.stdout.flush() rather than a simple print, things will work fine in that command line as well.

Community
  • 1
  • 1
Joshua Grigonis
  • 748
  • 5
  • 18