简体   繁体   中英

Run Python script in the background as a service

i want to run python script as a service. for that i followed instructions here .

for init script(myservice.sh), i copied as it is.

for 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". it successfully started.

when i send udp data, but nothing is happend to "output.txt". what is the problem here?

This process is formally referred to as daemonizing a Python script.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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