Package: daemon-application
daemon-applicationDescriptionA simple python package for creating daemon applications.Notice:Runs the application in daemon mode on Linux only. On Windows, the application runs in foreground model.Installpip install daemon-applicationUsageExample for raw APIsimport time
import threading
import signal
from daemon_application import daemon_start

stopflag = False

def main():
    def on_exit(*args, **kwargs):
        with open("backgroud.log", "a", encoding="utf-8") as fobj:
            print("process got exit signal...", file=fobj)
            print(args, file=fobj)
            print(kwargs, file=fobj)
        global stopflag
        stopflag = True
    signal.signal(signal.SIGTERM, on_exit)
    signal.signal(signal.SIGINT, on_exit)
    while not stopflag:
        time.sleep(1)
        print(time.time())

if __name__ == "__main__":
    print("start background application...")
    daemon_start(main, "background.pid", True)Example for DaemonApplicationimport time
from daemon_application import DaemonApplication

class HelloApplication(DaemonApplication):
    def main(self):
        while True:
            print("hello")
            time.sleep(1)

controller = HelloApplication().get_controller()

if __name__ == "__main__":
    controller()Example for DaemonApplication adding new global optionsimport time
import click
from daemon_application import DaemonApplication

class HelloApplication(DaemonApplication):

    def get_main_options(self):
        options = [
            click.option("-m", "--message", default="hello")
        ]
        return options + super().get_main_options()

    def main(self):
        while True:
            print(self.config["message"])
            time.sleep(1)

controller = HelloApplication().get_controller()

if __name__ == "__main__":
    controller()The output of the command help that added a new global optionUsage: example.py [OPTIONS] COMMAND [ARGS]...

Options:
  --pidfile TEXT          pidfile file path.
  --workspace TEXT        Set running folder
  --daemon / --no-daemon  Run application in background or in foreground.
  -c, --config TEXT       Config file path. Application will search config
                          file if this option is missing. Use sub-command
                          show-config-fileapaths to get the searching tactics.

  -m, --message TEXT
  --help                  Show this message and exit.

Commands:
  restart                Restart Daemon application.
  show-config-filepaths  Print out the config searching paths.
  start                  Start daemon application.
  stop                   Stop daemon application.Example of graceful-stop-application using daemon-application and graceful-sigterm.importtimeimportsignalimportloggingimportsigterm# pip install graceful-sigtermfromdaemon_applicationimportDaemonApplication_logger=logging.getLogger(__name__)classHelloApplication(DaemonApplication):defmain(self):# setup sigtermsigterm.setup()sigterm.setup(signal.SIGINT)sigterm.register_worker(self._main)sigterm.execute()def_main(self):# start application mainwhilenotsigterm.is_stopped():_logger.info("hello")time.sleep(1)_logger.info("gracefully stopped!")controller=HelloApplication().get_controller()if__name__=="__main__":controller()Start the application, and kill by the pid. The application output looks like:test@test daemon-application % python t1.py --no-daemon start
Start application without config file.
2023-09-11 10:13:44,186 INFO 7634 8205548160base daemon_start 174 Start application in FRONT mode, pid=7634.
2023-09-11 10:13:44,187 INFO 7634 8205548160sigterm setup 88 signal setup: sig=15, handler=<function default_handler at 0x100beaa20>
2023-09-11 10:13:44,187 INFO 7634 8205548160sigterm setup 88 signal setup: sig=2, handler=<function default_handler at 0x100beaa20>
2023-09-11 10:13:44,187 INFO 7634 8205548160sigterm execute 94 start workers...
2023-09-11 10:13:44,187 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:45,192 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:46,197 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:47,202 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:48,208 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:49,214 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:50,219 INFO 7634 6180237312t1 _main 19 hello
2023-09-11 10:13:50,404 INFO 7634 8205548160sigterm default_handler 51 get TERM signal, prepare to stop server...
2023-09-11 10:13:51,224 INFO 7634 6180237312t1 _main 21 gracefully stopped!
2023-09-11 10:13:51,225 INFO 7634 8205548160sigterm execute 101 worker <Thread(Thread-1 (_main), stopped daemon 6180237312)> end.
2023-09-11 10:13:51,225 INFO 7634 8205548160sigterm execute 104 main thread end.Look into the log, you will seegracefully stopped!. The kill command is not kill the main process, but set the is_stopped flag, and the application gracefully exit by it's logical controller.ConfigsConfig items and default valuespidfile: app.pidstop-timeout: 30stop-signal: SIGINTdaemon: Trueworkspace: ""loglevel: INFOlogfile: app.loglogfmt: defaultservices fieldsclass: class path string, e.g. zenutils.serviceutils.DebugServiceargs: []kwargs: {}NoteLogging is ENABLED aslogutils.setup(**self.config)by default.Test Passed With Pythons2.73.33.43.53.63.73.83.93.103.11Releasev2.0.0Remove rpc related parts.Notice:SimpleRpcApplication Based Application should change deps todaemon-application~=1.0.5.v1.0.5Change rpcutils, make it more easy to use.v0.5.10Use dictutils.deep_merge to update config.v0.5.9Unit test passed.v0.5.8Work with zenutils.socketserverutils.v0.5.7Improve the srpcd command.v0.5.6Add SimpleRpcServer class and srpcd command.v0.5.5Config in DaemonApplication is set to the dictutils.Object class for ease use while remaining compatible with all dict operations.v0.5.4Doc update.v0.5.3Add DaemonApplication.load_config, so that you can start DaemonApplication service directly by your code.Add stop_timeout for daemon_stop. If stop timeout, kill process tree by force.v0.5.2Add global options: loglevel, logfile, logfmt.Update default_config override mechanism.v0.4.4Fix the problem in sub-command stop.v0.4.3Deps on pyyaml.v0.4.2Remove a print() statement.v0.4.1Fix documents URLs.v0.4.0Remove fastutils deps.Add--configglobal command option for DaemonApplication.Provide a way to override the global options for subclass of DaemonApplication.The sub-commandrestartwill do juststartif the old application is not running or crashed.Use gitee.com source code hosting service.v0.3.3Fix show-config-filepaths.v0.3.2Add click deps in requirements.txtv0.3.1Add DaemonApplication.v0.3.0New wrapper.v0.2.1Old releases.