[英]End looping function on function return - Python
My question is a bit confusing so I will explain it by saying exactly what I am trying to do. 我的问题有点令人困惑,因此我将通过确切地说出我想做的事情来进行解释。
I just got a Raspberry Pi and am writing a Python project with it. 我刚得到一个Raspberry Pi,正在用它编写一个Python项目。 I have a function that makes a light blink on and off infinitely.
我有一个功能,可以使灯无限地闪烁。 I want to use the blinking light to show a status of a job (one that could take awhile).
我想使用闪烁的指示灯显示工作状态(可能需要一段时间)。
Here is the pseudo-code for what I am trying to do: 这是我要执行的操作的伪代码:
def blink():
while 1:
##light on##
time.sleep(.5)
##light off##
time.sleep(.5)
longRunningJob() #stop blinking when job returns
Any ideas? 有任何想法吗?
You may use a class to pass a stop variable and finish thread like this: 您可以使用一个类来传递stop变量并完成线程,如下所示:
import time
from threading import Thread
class Blink(Thread):
def __init__(self,starting_variable):
Thread.__init__(self)
print("starting variable: %s"%(starting_variable))
self.stop=False
def Stop(self):
self.stop = True
def blink(self):
print("light on")
##light on##
time.sleep(.5)
print("light off")
##light off##
time.sleep(.5)
def run(self):
while not self.stop:
self.blink()
print("exiting loop ...")
def longRunningJob():
for sleep_delay in range(5):
print("in longRunningJob with sleep: %s"%(sleep_delay))
time.sleep(sleep_delay)
blink=Blink("something")
blink.start()
longRunningJob()
blink.Stop()
print("END")
Here is the solution 这是解决方案
import threading
import time
RUNNING = False
def blink():
while RUNNING:
##light on##
time.sleep(.5)
##light off##
time.sleep(.5)
t = threading.Thread(target=blink)
RUNNING = True
t.start()
longRunningJob() #stop blinking when job returns
RUNNING = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.