为了让您的脚本等待,请使用time.sleep(num_seconds)
. time.time()
只返回当前时间;它根本不会让任何东西等待。
可能有一些代码处于休眠状态,而其他代码同时运行,做其他事情。但是,要做到这一点,您必须使用线程,这需要一些时间来适应。也许本教程会有用。
编辑:哦,也可以在没有线程的情况下执行此操作,但是您必须仔细跟踪变量。你的数学有点搞砸了。假设当 time.time() 为 1000 时,您的代码运行了。然后TimeReturned
是 1005。假设用户输入 1 秒钟Yes
。然后if TimeReturned > time.time()
检查if 1005 > 1001
,这是真的。您真正想要检查的是if time.time() > TimeReturned
- 当前时间是否晚于TimeReturned
.
此外,您的脚本不是交互式的,因此很难看到任何进展。尝试运行此脚本:
import time
survivors = 15
survivor_return_seconds = 10.0
time_survivors_left = None
while True:
action = raw_input("Type 'x' to make survivors leave, ENTER to see how many are left: ")
#check if survivors returned
if time_survivors_left is not None:
if time.time() >= time_survivors_left + survivor_return_seconds:
survivors += 5
time_survivors_left = None
print "Survivors came back!"
if action == 'x':
if time_survivors_left is not None:
print "Survivors already left! Wait a bit!"
else:
survivors -= 5
time_survivors_left = time.time()
print "There are %s survivors left." % (survivors,)
if time_survivors_left is not None:
print "5 survivors will return in %.2fs" % (
time_survivors_left + survivor_return_seconds - time.time())
示例输出:
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 15 survivors left.
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 15 survivors left.
Type 'x' to make survivors leave, ENTER to see how many are left: x
There are 10 survivors left.
5 survivors will return in 9.99s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 9.05s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 7.66s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 6.45s
Type 'x' to make survivors leave, ENTER to see how many are left: x
Survivors already left! Wait a bit!
There are 10 survivors left.
5 survivors will return in 5.73s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 4.15s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 2.90s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 1.72s
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 10 survivors left.
5 survivors will return in 0.48s
Type 'x' to make survivors leave, ENTER to see how many are left:
Survivors came back!
There are 15 survivors left.
Type 'x' to make survivors leave, ENTER to see how many are left:
There are 15 survivors left.
Type 'x' to make survivors leave, ENTER to see how many are left: