保持Python脚本运行,但允许调用函数

时间:2019-02-06 16:37:34

标签: python multithreading amazon-web-services callback iot

可能是一个愚蠢的问题,或者我问的是错误的问题,但这是我正在尝试做的事情。

我使用python作为在LabVIEW和AWS IoT之间进行通信的层。我可以轻松地从LabVIEW调用可与AWS进行通信的python函数;但是,为了通过来自AWS的回调获取消息,我需要保持python脚本运行。但是我知道如何保持它运行的唯一方法是一个无限循环,这使得它不再能够调用python函数。我认为这是一个多线程问题(我不擅长),我可以轻松地运行两个python脚本来执行此操作,但我宁愿让一个python脚本来处理所有问题。

这里有一些虚拟代码可以帮助可视化我正在尝试做的事情:

# This function is called from LabVIEW and sends data
def send_data_to_aws(msg):
    aws_publish(msg)

# This function is a callback from AWS and will get called.
# Even if I am in an infinite loop this function will be called
def callback_func(msg):
    send_to_labview(msg)

... Other AWS code to set up connections with IoT ...

myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath)
# This is how the client sets up the callback function.
myAWSIoTMQTTClient.onMessage = callback_func

while True:
    # Just keeping the code alive
    # so the callback function can be called
    # however because of this forever loop send_data_to_aws can no longer be called
    time.sleep(5)

0 个答案:

没有答案