Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the simplest way to daemonize a python script in Linux?

What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.

like image 282
edomaur Avatar asked Sep 22 '08 16:09

edomaur


People also ask

What is daemon process python?

Daemon processes in PythonTo execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.


1 Answers

See Stevens and also this lengthy thread on activestate which I found personally to be both mostly incorrect and much to verbose, and I came up with this:

from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr

if fork(): exit(0)
umask(0) 
setsid() 
if fork(): exit(0)

stdout.flush()
stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())

If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one

from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()

For security reasons you might consider any of these after demonizing

from os import setuid, setgid, chdir
from pwd import getpwnam
from grp import getgrnam
setuid(getpwnam('someuser').pw_uid)
setgid(getgrnam('somegroup').gr_gid)
chdir('/') 

You could also use nohup but that does not work well with python's subprocess module

like image 165
Florian Bösch Avatar answered Sep 20 '22 15:09

Florian Bösch