我有一个带红外传感器的Raspberry Pi。在我的Python脚本中有一个线程类,它监听一个imap服务器(捕获START或STOP等指令)。我的想法是现在通过电子邮件发送命令,一旦脚本收到命令,就应该禁用某些功能,直到收到新的命令。但主要问题是现在我不知道如何实现它。 感谢您提供有用且有用的建议。
def take_picture():
...
def take_video():
...
class EmailThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
....
if get_mail == 1:
if var_subject == 'STOP':
#TODO: stop take_picture(), take_video()
pass
elif var_subject == 'START':
#TODO: start take_picture(), take_video()
pass
else:
print u'Wrong command'
time.sleep(600) #google doesn't like many connections within 10min
def main():
# Start eMail Thread
email = EmailThread()
email.start()
try:
print "Waiting for PIR to settle ..."
# Loop until PIR output is 0
while GPIO.input(GPIO_PIR) == 1:
Current_State = 0
print "Ready"
# Loop until threadingusers quits with CTRL-C
while True :
# Read PIR state
Current_State = GPIO.input(GPIO_PIR)
if Current_State == 1 and Previous_State == 0:
counter = counter + 1
# PIR is triggered
start_time = time.time()
log_to_file('Motion Nr. %s detected!' % counter)
take_picture()
# Record previous state
Previous_State = 1
elif Current_State == 0 and Previous_State == 1:
# PIR has returned to ready state
stop_time=time.time()
print " Ready ",
elapsed_time=int(stop_time-start_time)
print " (Elapsed time : " + str(elapsed_time) + " secs)"
Previous_State = 0
except KeyboardInterrupt:
print "Quit "
# Reset GPIO settings
GPIO.cleanup()
if __name__ == '__main__':
main()
答案 0 :(得分:1)
我认为你的问题标题选择得很糟糕。我认为您尝试做的是启动/停止运行这些功能的线程。启动一个线程很容易,停止它稍微困难一些,取决于函数内部的功能。
您希望研究线程间通信方法,尤其是condition variables
。通常,只有在允许您执行此操作时才能正常停止线程,例如在条件变量上休眠时。
如果你实际上不想使用线程,而是周期性想要运行当前活动的函数,则需要实现一个调度程序 - 在最简单的情况下,调度程序只需重复循环通过活动函数列表,并调用它们。
我建议使用后者,因为线程主要只是引入了不必要的复杂性和错误来源,但是从你的问题来看,听起来你似乎已经决心做第一个。
答案 1 :(得分:1)
class ClassWithTheFunctions:
def __init__(self):
import types
#...
self.funcMap = {}
for o in self.__dict__:
if type(self.__dict__[o]) == types.FunctionType or type(self.__dict__[o]) == types.MethodType:
self.funcMap[self.__dict__[o]] = True
当你想要调用一个函数时,先检查它
if instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] :
funcIWantToCall()
如果要禁用某个功能:
instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] = False
或启用它:
instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] = True
答案 2 :(得分:0)
我认为self.enabled在这种情况下会起作用吗?
def __init__(self):
self.enabled=True
threading.Thread.__init__(self)
然后将enable切换为true / false?