[Tutor] time.sleep
Remco Gerlich
scarblac@pino.selwerd.nl
Wed, 22 Nov 2000 20:03:28 +0100
On Wed, Nov 22, 2000 at 10:47:21AM -0800, Mallett, Roger wrote:
> Concerning the time.sleep function I have a couple of questions.
>
> In TEST 1 (below), I placed a sleep between two prints. However, when the
> code was executed, the sleep occurred before the first print displayed to
> the screen.
> Question: Why did the sleep occur before "line 1" was printed to
> the screen?
Hmm, this doesn't happen when I try it. But then, I don't know about your
platform, how exactly you try it, etc. The output is probably buffered; it's
still in the buffer when the program sleeps, you only see the print when
the buffer is flushed later.
Two options that come to mind:
- Flush stdout before the sleep with sys.stdout.flush()
- Start Python with the -u option to disable all buffering on stdin, stdout
and stderr
> In TEST 2 (below), I attempted to pass in a value to sleep which resulted in
> an error. I also tried passing in a long, same results.
> Question: Why the error? How should I pass a value into sleep?
>
> TEST 2
> >>> def test2(time):
> ... print 'line 1'
> ... time.sleep(time)
> ... print 'line 2'
> ...
> >>> test2(1)
> line 1
> Traceback (innermost last):
> File "<interactive input>", line 1, in ?
> File "<interactive input>", line 3, in test2
> AttributeError: 'int' object has no attribute 'sleep'
> >>>
You called your local variable "time". So "time.sleep" is not the function
"sleep" in module "time", but instead the method "sleep" on the number 1...
Give your variable a name that doesn't clash with the module's name.
Remco Gerlich