如何从应用程序内部重新启动python应用程序

2024-04-24 22:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个Django应用程序,它让用户通过安装向导。向导完成后,应用程序需要重新启动才能选择必要的设置。你知道吗

该应用程序运行在ubuntu18.04上,并使用supervisord进行监控。你知道吗

理想情况下,我希望调用systemctl restart监督服务来自Django应用程序本身。你知道吗

所以我试过了

import subprocess
subprocess.run("systemctl restart supervisord.service")

但是,此操作失败,并出现以下错误:

FileNotFoundError [Errno 2] No such file or directory: 'systemctl restart supervisord.service': 'systemctl restart supervisord.service'

这里有this question,但这是一个较老的问题,答案依赖于操作系统。*而截至发帖时,子流程似乎是访问操作系统功能的首选方式


Tags: djangorun用户import程序运行应用程序错误service
2条回答

要获得更简洁的方法来启动自己的python程序,请执行以下操作:

import os
import sys
import psutil
import logging

def restart_program():
    """Restarts the current program, with file objects and descriptors
       cleanup
    """

    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

    python = sys.executable
    os.execl(python, python, *sys.argv)

看到我的错误了。命令的运行方式应为:

subprocess.run(["systemctl", "restart", "supervisor.service"])

资料来源:http://queirozf.com/entries/python-3-subprocess-examples

相关问题 更多 >