Python睡眠在循环中不起作用? [英] Python sleep doesn't work right in a loop?

查看:921
本文介绍了Python睡眠在循环中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需要一小段代码就可以在两个状态之间切换......


导入时间

for i in range(4):

打印''开''

time.sleep(1)

打印''关''

时间.sleep(1)


....应该在一秒钟的停顿时间内打开和关闭四次。当我运行这个时,循环暂停整整8秒,然后立即打印Ons

和Offs。这有什么用?

Just a simple bit of code to toggle between two state at intervals...

import time
for i in range(4):
print ''On''
time.sleep(1)
print ''Off''
time.sleep(1)

.... SHOULD toggle On and Off four times with one-second pauses. When I
run this, the loop pauses the full eight seconds then prints the Ons
and Offs all at once. What''s up with that?

推荐答案

对我来说它运作正常。看来你的终端没有正确刷新stdout

。你在写什么样的终端?

For me it works fine. It seems that for you stdout is not flushed
correctly in your terminal. What kind of terminal are you writing to?


ri********@yahoo.com 写道:
ri********@yahoo.com wrote:
只是一小段代码可以间隔地在两个状态之间切换......
进口时间
我在范围内(4):
打印''开''
time.sleep(1)
打印''关''
time.sleep(1)

...应该在一秒钟的暂停状态下打开和关闭四次。当我运行它时,循环暂停整整8秒,然后立刻打印Ons
和Offs。这有什么用呢?
Just a simple bit of code to toggle between two state at intervals...

import time
for i in range(4):
print ''On''
time.sleep(1)
print ''Off''
time.sleep(1)

... SHOULD toggle On and Off four times with one-second pauses. When I
run this, the loop pauses the full eight seconds then prints the Ons
and Offs all at once. What''s up with that?




适用于我 - 在使用linux的终端上。但是不起作用的是:


python /tmp/test.py | cat


(test.py当然包含你的代码)原因是使用了缓冲管道

。试试这个:


导入时间,sys

for i in range(4):

print''On''< br $>
sys.stdout.flush()

time.sleep(1)

打印''关''

sys.stdout.flush()

time.sleep(1)


-

问候,


Diez B. Roggisch



Works for me - on a terminal using linux. BUT what not works is this:

python /tmp/test.py | cat

(test.py contains your code of course) The reason is buffered pipes being
used. Try this:

import time, sys
for i in range(4):
print ''On''
sys.stdout.flush()
time.sleep(1)
print ''Off''
sys.stdout.flush()
time.sleep(1)

--
Regards,

Diez B. Roggisch


ri * *******@yahoo.com 写道:
...应该以一秒钟的暂停来打开和关闭四次。当我运行它时,循环暂停整整8秒,然后立刻打印Ons
和Offs。有什么用呢?
... SHOULD toggle On and Off four times with one-second pauses. When I
run this, the loop pauses the full eight seconds then prints the Ons
and Offs all at once. What''s up with that?




运行你的脚本:


python -u script.py

无缓冲输出。



Run your script as:

python -u script.py

for unbuffered output.


这篇关于Python睡眠在循环中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆