我有一个我已订阅并持续接收数据的 mqtt 代理。
代码
# broker.py
import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
print("message received ")
# do some calculations on the data recieved.
target_variable = #stored after the calculations.
client.on_message=on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address, port=port,) #connect to broker
client.subscribe("topic")
client.loop_forever() #stop the loop
所以当我运行这个python脚本时,这是一个永远的过程,不断更新目标变量。我想在不同的脚本中使用这个目标变量。
代码
# main.py
import schedule
from broker.py import target_variable
def job():
# use target_variable and perform some taks
print(target_variable)
schedule.every(60).seconds.do(job)
while True:
schedule.run_pending()
这也是一个永久进程,每 60 秒运行一次作业。我想在 main.py 中使用broker.py 中的 target_variable。
我无法在单个脚本中运行这两件事,如果我有单独的脚本并尝试在 main.py 中加载broker.py,broker.py只会执行而不会结束。
有人可以帮我解决这个问题吗?
最佳答案
请将它们作为函数并在单个脚本中将它们作为守护线程启动,以便它将永远运行,直到您停止脚本。 一个例子是:
def myfunc1(i):
# any job you want to do
pass
def myfunc2():
# any job you want to do
pass
t1 = Thread(target=myfunc1, args=(,))
t1.daemon = True
t1.start()
t2 = Thread(target=myfunc2, args=(,))
t2.daemon = True
t2.start()
关于python - 两个永无休止的Python脚本之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305506/