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.


Asked by: Edward878 | Posted: 05-10-2021






Answer 1

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

Answered by: Cherry458 | Posted: 06-11-2021



Answer 2

nohup

Creating a daemon the Python way

Answered by: Chelsea371 | Posted: 06-11-2021



Answer 3

I have recently used Turkmenbashi :

$ easy_install turkmenbashi
import Turkmenbashi

class DebugDaemon (Turkmenbashi.Daemon):

    def config(self):
        self.debugging = True

    def go(self):
        self.debug('a debug message')
        self.info('an info message')
        self.warn('a warning message')
        self.error('an error message')
        self.critical('a critical message')

if __name__=="__main__":
    d = DebugDaemon()
    d.config()
    d.setenv(30, '/var/run/daemon.pid', '/tmp', None)
    d.start(d.go)

Answered by: Ada642 | Posted: 06-11-2021



Answer 4

If you do not care for actual discussions (which tend to go offtopic and do not offer authoritative response), you can choose some library that will make your tast easier. I'd recomment taking a look at ll-xist, this library contains large amount of life-saving code, like cron jobs helper, daemon framework, and (what is not interesting to you, but is really great) object-oriented XSL (ll-xist itself).

Answered by: Adrian819 | Posted: 06-11-2021



Answer 5

Use grizzled.os.daemonize:

$ easy_install grizzled

>>> from grizzled.os import daemonize
>>> daemon.daemonize()

To understand how this works or to do it yourself, read the discussion on ActiveState.

Answered by: Adelaide741 | Posted: 06-11-2021



Similar questions

scripting - How do I check out a file from perforce in python?

I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.


scripting - python as a "batch" script (i.e. run commands from python)

I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file. how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. So, just running a program and printing the output won't...


scripting - Make python enter password when running a csh script

I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: import commands commands.getoutput('server stop')


scripting - Python code for sorting files into folders

Python 2.5.1 http://www.cgsecurity.org/wiki/After_Using_PhotoRec I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks : [EDIT2: Two points: This question was voted down because it was a...


python - How can I call a DLL from a scripting language?

I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth). I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a p...


scripting - Change directory to the directory of a Python script

How do I change directory to the directory with my Python script in? So far, I figured out I should use os.chdir and sys.argv[0]. I'm sure there is a better way then to write my own function to parse argv[0].


php - Get remote text file, process, and update database - approach and scripting language to use?

I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron. I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data...


scripting - cProfile and Python: Finding the specific line number that code spends most time on

I'm using cProfile, pstats and Gprof2dot to profile a rather long python script. The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time. Any idea's how to get this additional information? (By the way, I'm using Python 2.6 on OSX snow leopard if that h...


php - How do scripting languages use sockets?

Python, Perl and PHP, all support TCP stream sockets. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine? When a client connects to a specific port, how does the script file get invoked? Does the script s...


html - Python for web scripting

I'm just starting out with Python and have practiced so far in the IDLE interface. Now I'd like to configure Python with MAMP so I can start creating really basic webapps — using Python inside HTML, or well, vice-versa. (I'm assuming HTML is allowed in Python, just like PHP? If not, are there any modules/template engines for that?) What modules do I need to install to run .py from my localhost? Googling a bit, it s...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top