【问题标题】:Slow or no response from read pickle file读取泡菜文件的响应缓慢或没有响应
【发布时间】:2016-07-08 11:44:16
【问题描述】:

我正在开发一个项目,该项目包含一个处理“时间”和“交通灯”参数的网络服务器并将其保存到 pickle 文件中,另一个脚本加载 pickle 并将其用于 mqtt 客户端

import pickle
import paho.mqtt.client as mqtt
from datetime import datetime, date, time
from threading import Timer
date=datetime.now()
print date
try:
    while True:
        fp = open("shared.pkl", 'rb')
        shared = pickle.load(fp)
        if date < shared["now"] :
            time= shared["time"]
            light = shared["light"]
            date = shared["now"]
            fp.close()
            time= int(time)
            def pub (s):
                client.publish("traffic/light1", payload = s ,qos=0, retain=False)
            t= Timer(time , pub,[light])
            t.start()
            print time
            print light
            print date




        client = mqtt.Client()


        client.connect("localhost", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.

        client.loop(timeout=1.0, max_packets=1)

except (EOFError, UnpicklingError):
    pass

它运行良好,但有时它不发布或不读取 pkl 文件! 有什么建议吗?

【问题讨论】:

  • 也许更详细的问题是什么?请说明,你期望什么,你观察什么。谢谢。
  • 假设没有 MQTT 错误,循环只会运行一次,因为它会在 client.loop() 调用时永远阻塞。这意味着它只会打开并从文件中读取一次。
  • loop() 不会阻止,loop_forever() 会。
  • 哇!是的,今天发生的事情太多了

标签: python python-2.7 pickle mqtt paho


【解决方案1】:

不用看得太仔细,下面这样的东西应该可以完成这项工作。

调用client.loop() 只是处理一点网络流量,并不能保证调用它之后所有的流量都会被发送。使用 loop_start()loop_forever() 取决于您是否需要异步/阻塞行为。

client = mqtt.Client()
client.connect("localhost", 1883, 60)

client.loop_start()

print date

while True:
    try:
        fp = open("shared.pkl", 'rb')
        shared = pickle.load(fp)
        fp.close()
    except (EOFError, UnpicklingError):
        continue

    if date < shared["now"] :
        time= shared["time"]
        light = shared["light"]
        date = shared["now"]

        time= int(time)
        def pub (s):
            client.publish("traffic/light1", payload = s ,qos=0, retain=False)
        t= Timer(time , pub,[light])
        t.start()
        print time
        print light
        print date

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2021-08-17
    • 2023-03-12
    相关资源
    最近更新 更多