简体   繁体   English

作为服务在后台运行Python脚本

[英]Run Python script in the background as a service

i want to run python script as a service. 我想将python脚本作为服务运行。 for that i followed instructions here . 为此,我按照这里的指示进行。

for init script(myservice.sh), i copied as it is. 对于初始化脚本(myservice.sh),我照原样复制了。

for myservice.py , 对于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()

When i start service "sudo /etc/init.d/myservice.sh start". 当我启动服务“ sudo /etc/init.d/myservice.sh启动”时。 it successfully started. 它成功启动。

when i send udp data, but nothing is happend to "output.txt". 当我发送udp数据时,“ output.txt”没有任何反应。 what is the problem here? 这里有什么问题?

This process is formally referred to as daemonizing a Python script. 此过程正式称为守护Python脚本。

I am going to assume both your init script and code are working correctly, likely it is an issue there. 我将假设您的初始化脚本和代码都正常工作,这可能是一个问题。

However, aside from this problem, use the logger class when daemonizing Python scripts. 但是,除此问题外,在守护Python脚本时使用logger类。 There are too many issues in attempting to implement logging in such a crude way yourself for a background process. 尝试以一种粗略的方式自己为后台进程实现日志记录存在太多问题。

This is the same in the example link you provided, take a look here for why: Maintaining Logging and/or stdout/stderr in Python Daemon 这与您提供的示例链接相同,请查看以下原因: 在Python守护进程中维护日志记录和/或stdout / stderr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM