How do you create a daemon in Python?

后端 未结 16 1700
轻奢々
轻奢々 2020-11-22 01:55

Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion und

相关标签:
16条回答
  • 2020-11-22 02:48

    I modified a few lines in Sander Marechal's code sample (mentioned by @JeffBauer in the accepted answer) to add a quit() method that gets executed before the daemon is stopped. This is sometimes very useful.

    Here it is.

    Note: I don't use the "python-daemon" module because the documentation is still missing (see also many other SO questions) and is rather obscure (how to start/stop properly a daemon from command line with this module?)

    0 讨论(0)
  • 2020-11-22 02:49

    Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:

    [Unit]
    Description=Python daemon
    After=syslog.target
    After=network.target
    
    [Service]
    Type=simple
    User=<run as user>
    Group=<run as group group>
    ExecStart=/usr/bin/python <python script home>/script.py
    
    # Give the script some time to startup
    TimeoutSec=300
    
    [Install]
    WantedBy=multi-user.target
    

    I prefer this method because a lot of the work is done for you, and then your daemon script behaves similarly to the rest of your system.

    -Orby

    0 讨论(0)
  • 2020-11-22 02:50

    YapDi is a relatively new python module that popped up in Hacker News. Looks pretty useful, can be used to convert a python script into daemon mode from inside the script.

    0 讨论(0)
  • 2020-11-22 02:50

    Though you may prefer the pure Python solution provided by the python-daemon module, there is a daemon(3) function in libc -- at least, on BSD and Linux -- which will do the right thing.

    Calling it from python is easy:

    import ctypes
    
    ctypes.CDLL(None).daemon(0, 0) # Read the man-page for the arguments' meanings
    

    The only remaining thing to do is creation (and locking) of the PID-file. But that you can handle yourself...

    0 讨论(0)
提交回复
热议问题