How do you create a daemon in Python?

后端 未结 16 1706
轻奢々
轻奢々 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:41

    I am afraid the daemon module mentioned by @Dustin didn't work for me. Instead I installed python-daemon and used the following code:

    # filename myDaemon.py
    import sys
    import daemon
    sys.path.append('/home/ubuntu/samplemodule') # till __init__.py
    from samplemodule import moduleclass 
    
    with daemon.DaemonContext():
        moduleclass.do_running() # I have do_running() function and whatever I was doing in __main__() in module.py I copied in it.
    

    Running is easy

    > python myDaemon.py
    

    just for completeness here is samplemodule directory content

    >ls samplemodule
    __init__.py __init__.pyc moduleclass.py
    

    The content of moduleclass.py can be

    class moduleclass():
        ...
    
    def do_running():
        m = moduleclass()
        # do whatever daemon is required to do.
    

提交回复
热议问题