守护 Python 脚本实现 Paho

如何解决守护 Python 脚本实现 Paho

我有一个 Python 脚本,它实现了 Paho 库以订阅和重新发布来自 Mosquitto 服务器的 MQTT 主题。当我从终端调用它时,我的脚本工作正常。什么让我绊倒是试图守护脚本运行无人看管。我正在使用 daemonize 库,虽然我可以让脚本作为守护程序启动,但它实际上没有任何事情。当我运行非守护程序脚本时,我看到在我指定的端点收到了 MQTT 消息,但是当相同的脚本作为守护程序运行时,我的接收端点没有显示任何消息。我包括了非守护程序和守护程序脚本以供参考。

关于为什么非守护脚本有效而守护脚本不起作用的任何想法?

非守护进程

import paho.mqtt.client as mqtt
import random
import json
import time

#replace [device-id] with your device you created in IoT Hub.
iothubmqtttopic = "devices/MoxieSensorsBHM/messages/events/"

#define on_connect function
def on_connect(client,userdata,flags,rc):
        print("Connected with result code " + str(rc))
        client.subscribe("MW/oneal/Tag/#")

#define on_message function - this function translates the incoming topic
#and publishes to the specified topic for IoT Hub
def on_message(client,message):
        global iothubmqtttopic
        topic = message.topic
        if(topic != iothubmqtttopic):

                #extract the sensor ID from the topic
                splitTopic = topic.split("/") #split the topic into a list
                sensorID = splitTopic[3] #the 3rd item in the list is the sensor ID
                msgType = splitTopic[4] #the 4th item in the list is the type (e.g. status,UWB)

                #convert the json response to a python dictionary object
                m_decode = str(message.payload.decode("utf-8"))
                m_in = json.loads(m_decode)

                #get current time for timestamp
                ts = time.gmtime()
                tsFormatted = time.strftime("%Y-%m-%d %H:%M:%S",ts)

                #add new elements to the dictionary for topic and sensor ID
                m_in["topic"] = topic
                m_in["sensorID"] = sensorID
                m_in["messageType"] = msgType
                m_in["timestamp"] = tsFormatted

                #set the propertybag for IoT Hub
                propertyBag = "topic=" + topic + "&sensorID=" + sensorID + "&messageType=" + msgType
                print(propertyBag)

                #convert back to JSON
                m_encode = json.dumps(m_in)

                #create an array of all the possible sensor IDs

                #print to screen and publish to IoT Hub
                print("Topic: ",topic)
                print("Message received: ",m_encode)
                print("IoT Hub Topic: ",iothubmqtttopic)
                client.publish(iothubmqtttopic,m_encode)

# replace <broker address> with the FQDN or IP address of your MQTT broker
broker_address="localhost"

#create the client and connect to the broker
print("creating new instance")
client = mqtt.Client("iottopicxlate" + str(random.randrange(1,1000000))) #create new instance
client.on_message=on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address) #connect to broker
client.on_connect = on_connect #attach function to callback

client.loop_forever() #stop the loop

守护进程

import paho.mqtt.client as mqtt
import random
import json
import time
import os,sys
from daemonize  import Daemonize

def main():
        #replace [device-id] with your device you created in IoT Hub.
        iothubmqtttopic = "devices/MoxieSensorsBHM/messages/events/"

        #define on_connect function
        def on_connect(client,rc):
                #print("Connected with result code " + str(rc))
                client.subscribe("MW/oneal/Tag/#")

        #define on_message function - this function translates the incoming topic
        #and publishes to the specified topic for IoT Hub
        def on_message(client,message):
                global iothubmqtttopic
                topic = message.topic
                if(topic != iothubmqtttopic):

                        #extract the sensor ID from the topic
                        splitTopic = topic.split("/") #split the topic into a list
                        sensorID = splitTopic[3] #the 3rd item in the list is the sensor ID
                        msgType = splitTopic[4] #the 4th item in the list is the type (e.g. status,UWB)

                        #convert the json response to a python dictionary object
                        m_decode = str(message.payload.decode("utf-8"))
                        m_in = json.loads(m_decode)

                        #get current time for timestamp
                        ts = time.gmtime()
                        tsFormatted = time.strftime("%Y-%m-%d %H:%M:%S",ts)

                        #add new elements to the dictionary for topic and sensor ID
                        m_in["topic"] = topic
                        m_in["sensorID"] = sensorID
                        m_in["messageType"] = msgType
                        m_in["timestamp"] = tsFormatted

                        #set the propertybag for IoT Hub
                        propertyBag = "topic="+topic+"&sensorID="+sensorID+"&messageType="+msgType
                        #print(propertyBag)

                        #convert back to JSON
                        m_encode = json.dumps(m_in)

                        #print to screen and publish to IoT Hub
                        print("Topic: ",topic + propertyBag)
                        print("Message received: ",m_encode)
                        client.publish(iothubmqtttopic,m_encode)

        # replace <broker address> with the FQDN or IP address of your MQTT broker
        broker_address="localhost"

        #create the client and connect to the broker
        #print("creating new instance")
        client = mqtt.Client("iottopicxlate" + str(random.randrange(1,1000000))) #create new instance
        client.on_message=on_message #attach function to callback
        #print("connecting to broker")
        client.connect(broker_address) #connect to broker
        client.on_connect = on_connect #attach function to callback

        client.loop_forever() #stop the loop

#start the daemon
topictransdpid = os.path.basename(sys.argv[0])
pidfile = "topictransd.pid"
daemon = Daemonize(app = "topictransd",pid = pidfile,action = main)
daemon.start()

更新 文森特,我正在尝试执行您的建议以写入文件进行调试。请耐心等待,因为我正在快速学习 Python。我已将以下代码片段添加到脚本的非守护程序(即工作)版本中的 on_message 函数中,并且我看到了写入“调试”目录中文本文件的消息。当我在守护程序版本中实现相同的片段时,没有写入任何文件。所以当我的守护进程运行时,它实际上并没有做任何事情。

                f = open("debug/" + sensorID+tsFormatted + ".txt","x")
                f.write(m_encode)
                f.close

对我遗漏的东西有什么想法吗?

更新 2 我实现了一个简单的记录器,用于在脚本启动时编写调试消息,并在 daemonize 调用 main() 函数时编写另一个记录器。我的日志文件有一个启动脚本的条目,但是没有一个条目用于调用 main() 时 - 好像 daemonize 没有执行 main() 函数?这是我启用了记录器的更新后的守护程序脚本:

import paho.mqtt.client as mqtt
import random
import json
import time
import logging
import os,sys
from daemonize  import Daemonize

def main():
        logger.warning("main has been started") # write a log file entry to indicate main has been called by daemonize
        #replace [device-id] with your device you created in IoT Hub.
        iothubmqtttopic = "devices/MoxieSensorsBHM/messages/events/"

        #define on_connect function
        def on_connect(client,ts)

                        #add new elements to the dictionary for topic and sensor ID
                        m_in["topic"] = topic
                        m_in["sensorID"] = sensorID
                        m_in["messageType"] = msgType
                        m_in["timestamp"] = tsFormatted

                        #set the propertybag for IoT Hub
                        propertyBag = "topic="+topic+"&sensorID="+sensorID+"&messageType="+msgType
                        #print(propertyBag)

                        #convert back to JSON
                        m_encode = json.dumps(m_in)

                        #print to screen and publish to IoT Hub
                        #print("Topic: ",topic + propertyBag)
                        #print("Message received: ",m_encode)

                        #write the message to a debug file
                        f = open("debug/" + sensorID+tsFormatted + ".txt","w")
                        f.write(m_encode)
                        f.close

        # replace <broker address> with the FQDN or IP address of your MQTT broker
        broker_address="localhost"

        #create the client and connect to the broker
        #print("creating new instance")
        client = mqtt.Client("iottopicxlate" + str(random.randrange(1,1000000))) #create new instance

        #create a logger
        #logging.basicConfig(level=logging.DEBUG,filename="topictransd.log",format="%(asctime)s %(message)s",filemode="w")
        #logger = logging.getLogger()
        #client.enable_logger(logger)

        client.on_message=on_message #attach function to callback
        #print("connecting to broker")
        client.connect(broker_address) #connect to broker
        client.on_connect = on_connect #attach function to callback

        #start the loop
        client.loop_forever()

#start the daemon
logging.basicConfig(level=logging.DEBUG,filemode="w")
logger = logging.getLogger()

pidfile = "topictransd.pid"
logger.warning("successfully started the script") # write a log file entry to indicate the script has successfully started
daemon = Daemonize(app = "topictransd",action = main)
daemon.start()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-