Python 守护进程打包最佳实践

2024-02-02

我有一个用 python 编写的工具,通常应该作为守护进程运行。打包此工具进行分发的最佳实践是什么,特别是应如何处理设置文件和守护进程可执行文件/脚本?

相关地,是否有任何通用工具可用于设置守护进程以在启动时运行,以适合给定的平台(即initLinux 上的脚本,Windows 上的服务,launchd在 os x 上)?


我发现帮助 init.d 脚本的最佳工具是“start-stop-daemon”。它将运行任何应用程序、监视 run/pid 文件、在必要时创建它们、提供停止守护进程、设置进程用户/组 ID 的方法,甚至可以将您的进程置于后台。

例如,这是一个可以启动/停止 wsgi 服务器的脚本:

#! /bin/bash

case "$1" in
  start)
    echo "Starting server"

    # Activate the virtual environment
    . /home/ali/wer-gcms/g-env/bin/activate

    # Run start-stop-daemon, the $DAEMON variable contains the path to the
    # application to run
    start-stop-daemon --start --pidfile $WSGI_PIDFILE \
        --user www-data --group www-data \
        --chuid www-data \
        --exec "$DAEMON"
    ;;
  stop)
    echo "Stopping WSGI Application"

    # Start-stop daemon can also stop the application by sending sig 15
    # (configurable) to the process id contained in the run/pid file
    start-stop-daemon --stop --pidfile $WSGI_PIDFILE --verbose
    ;;
  *)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/wsgi-application.sh {start|stop}"
    exit 1
    ;;
esac

exit 0

您还可以看到一个如何将它与 virtualenv 一起使用的示例,我总是推荐它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 守护进程打包最佳实践 的相关文章

随机推荐