两个永无止境的 python 脚本之间的交互

Interaction between two never ending python scripts

我订阅了一个 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()