读取pickle文件的响应缓慢或没有响应

时间:2016-07-08 11:44:17

标签: python python-2.7 pickle mqtt paho

我正在开发一个包含处理" time"的网络服务器的项目。和交通灯"参数并将其保存到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文件!! 有什么建议吗?

1 个答案:

答案 0 :(得分: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