スクリプトを待機させるには、 を使用しますtime.sleep(num_seconds)
。time.time()
現在の時刻を返すだけです。何も待たせることはありません。
一部のコードがスリープ状態であるにもかかわらず、他のコードが同時に実行され、別のことを実行している可能性があります。ただし、これを行うには、慣れるまでに時間がかかるスレッドを使用する必要があります。おそらく、このチュートリアルは役に立ちます。
編集:ああ、スレッドなしでこれを行うことも可能ですが、変数を注意深く追跡する必要があります。あなたは数学を少し台無しにしました。time.time() が 1000 のときにコードが実行されたとします。次にTimeReturned
1005 です。ユーザーが入力するのに 1 秒かかったとしYes
ます。次に、if TimeReturned > time.time()
チェックしますif 1005 > 1001
。これは True です。本当に確認したかったのは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: