我来自 Node,在那里处理异步设计就像添加回调和继续你的生活一样简单。我正在尝试用 python 编写一些应用程序,但我没有取得同样的成功,而且我正在努力寻找要搜索的内容,因为似乎没有直接的等价物。
这是我运行 MQTT 消息传递客户端并等待来自传感器的状态更改信号的示例。
import paho.mqtt.client as mqtt
from ouimeaux.environment import Environment
from ouimeaux.signals import receiver, statechange
def on_connect(client, userdata, rc):
print('Connected with result code '+str(rc))
client.subscribe('lights/#')
def turn_lights_on(client, userdata, rc):
for (x, value) in enumerate(devices['switches']):
devices['switches'][x].on()
def turn_lights_off(client, userdata, rc):
for (x, value) in enumerate(devices['switches']):
devices['switches'][x].off()
def reply_with_devices(client, userdata, rc):
for (x, value) in enumerate(devices['switches']):
client.publish('devices/new', switches[x])
for (x, value) in enumerate(devices['motions']):
client.publish('devices/new', motions[x])
def on_switch(switch):
print "Switch found: ", switch.name
devices['switches'].append(switch)
def on_motion(motion):
print "Motion found: ", motion.name
devices['motions'].append(motion)
client = mqtt.Client("wemo_controller")
client.on_connect = on_connect
client.message_callback_add('lights/on', turn_lights_on)
client.message_callback_add('lights/off', turn_lights_off)
client.message_callback_add('devices/discover', reply_with_devices)
client.connect('localhost', 1883, 60)
print 'Running WEMO controller - listening for messages on localhost:1883'
devices = { 'switches': [], 'motions': [] }
env = Environment(on_switch, on_motion)
env.start()
env.discover(seconds=3)
switch = env.get_switch('Desk lights')
@receiver(statechange)
def motion(sender, **kwargs):
print 'A THING HAPPENED'
print "{} state is {state}".format(sender.name, state="on" if kwargs.get('state') else "off")
env.wait()
client.loop_forever()
这两个库似乎都有自己的方式来保持线程,但我似乎一次只能有一个阻塞和监听。我觉得线程可能是答案,但我正在努力研究如何实现它,但不确定它是否正确。我也对 wait() 和 loop_forever() 的实际作用感到困惑。
我正在寻找的答案是解决此问题的“python”方法。
最佳答案
您可能想查看 Twisted framework
“Twisted 是一个用 Python 编写的事件驱动网络引擎” 它专为构建异步网络应用程序而设计。
特别是阅读 reactor ,并使用 Deffered()注册回调
关于python - 在 Python 中处理异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899679/