flask 服务管理脚本
  Uz9KIXKpP3pL 2023年11月02日 55 0
import os
import sys
import time
import signal
from subprocess import Popen, PIPE, DEVNULL

APP_DIR = '/root/Flask'
APP_FILE = 'manage.py runserver'
PID_FILE = '/var/run/Flask_app.pid'

def start_app():
    command = f'cd {APP_DIR} &&  python3.8 {APP_FILE}'
    process = Popen(command, shell=True, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setsid)
    with open(PID_FILE, 'w') as pid_file:
        pid_file.write(str(process.pid))

def stop_app():
    if os.path.exists(PID_FILE):
        with open(PID_FILE, 'r') as pid_file:
            pid = int(pid_file.read().strip())
            os.killpg(pid, signal.SIGTERM)
        os.remove(PID_FILE)

def restart_app():
    stop_app()
    time.sleep(1)
    start_app()

def status_app():
    if os.path.exists(PID_FILE):
        with open(PID_FILE, 'r') as pid_file:
            pid = int(pid_file.read().strip())
            try:
                os.kill(pid, 0)
                return f"Your app is running (PID: {pid})"
            except ProcessLookupError:
                return "Your Flask app is not running"
    else:
        return "Your Flask  app is not running"

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python3.8 your_app_service.py [start|stop|restart|status]")
        sys.exit(1)

    action = sys.argv[1]

    if action == 'start':
        start_app()
        print("Your Flask app has been started.")
    elif action == 'stop':
        stop_app()
        print("Your Flask app has been stopped.")
    elif action == 'restart':
        restart_app()
        print("Your Flask app has been restarted.")
    elif action == 'status':
        status = status_app()
        print(status)    
    else:
        print("Invalid action. Usage: python3 your_app_service.py [start|stop|restart|status]")
        sys.exit(1)
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  9JCEeX0Eg8g4   2023年11月25日   41   0   0 ednpython
  38gcbVXUBcLA   2023年11月19日   29   0   0 python缩进
  6tuRdFP5lxfF   2023年11月22日   34   0   0 python日志记录