只有在状态为真的情况下,如何在一定时间后才在 python 中使用函数?



使用 python3,我想每 10 秒运行一次函数。但仅当变量仍处于"打开"状态时,该函数才会再次运行。我正在使用random.random函数随机模拟开/关。如果 random.random 的值小于 0.5,则变量y打开,y如果变量大于 0.5,则变量 关闭。 使用 threading.timer 我将函数设置为每 10 秒运行一次。为简单起见,我只是在函数的主体中加入print("x")

import threading
import random
def machine_on():
threading.Timer(10.0, machine_on).start() #called every 10 seconds 
print("x")
y=0        
if y < 0.5:  
machine_on()
y = random.random()
else:
sys.exit()

运行这些代码后,我的计算机进入无限循环。你知道我的代码有什么问题吗? 如何解决问题?

import random
import time
def machine_on():
print("x")
y=0         
while True:
if y < 0.5:  
machine_on()
y = random.random()
print(y)
time.sleep(10) 
else:
break

你可以在线程中做到这一点

def print_x():
global y
for i in xrange(1000000): # or use while True
if y > 0.5:
print('x')
time.sleep(10)

最新更新