Daemonizing python's BaseHTTPServer

后端 未结 6 1885
南方客
南方客 2021-02-05 20:35

I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I tr

6条回答
  •  野的像风
    2021-02-05 21:15

    Here's how to do this with the python-daemon library:

    from BaseHTTPServer import (HTTPServer, BaseHTTPRequestHandler)
    import contextlib
    
    import daemon
    
    from my_app_config import config
    
    # Make the HTTP Server instance.
    server = HTTPServer(
        (config['HTTPServer']['listen'], config['HTTPServer']['port']),
        BaseHTTPRequestHandler)
    
    # Make the context manager for becoming a daemon process.
    daemon_context = daemon.DaemonContext()
    daemon_context.files_preserve = [server.fileno()]
    
    # Become a daemon process.
    with daemon_context:
        server.serve_forever()
    

    As usual for a daemon, you need to decide how you will interact with the program after it becomes a daemon. For example, you might register a systemd service, or write a PID file, etc. That's all outside the scope of the question though.

    In particular, it's outside the scope of the question to ask: once it's become a daemon process (necessarily detached from any controlling terminal), how do I stop the daemon process? That's up to you to decide, as part of defining the program's behaviour.

提交回复
热议问题