运行 Python 后台脚本作为服务

Run Python script in the background as a service

我想 运行 python 脚本作为服务。为此,我遵循了说明 here

对于初始化脚本(myservice.sh),我照原样复制了。

对于 myservice.py ,

import sys, struct
from socket import *

SIZE = 1024      # packet size

hostName = gethostbyname('0.0.0.0')

mySocket  = socket( AF_INET, SOCK_DGRAM )
mySocket.bind((hostName,18736))

repeat = True
while repeat:
   (data,addr) = mySocket.recvfrom(SIZE)
   data = struct.unpack('d',data)
   data=int(data[0])

   file = open("output.txt", "w")
   file.write(str(data))
   file.close()

当我开始服务时 "sudo /etc/init.d/myservice.sh start"。 它成功启动了。

当我发送 udp 数据时,"output.txt" 没有任何反应。这里有什么问题?

此过程正式称为 Python 脚本守护进程。

我假设您的初始化脚本和代码都在正常工作,这可能是那里的一个问题。

但是,除此问题外,在守护 Python 脚本时使用记录器 class。尝试自己以这种粗略的方式为后台进程实现日志记录存在太多问题。

这与您提供的示例 link 相同,请在此处查看原因:Maintaining Logging and/or stdout/stderr in Python Daemon