Python脚本不能正确地重新启动自己

2024-09-28 05:22:18 发布

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

我有一个Python脚本,我想让它自己重新启动。我在谷歌上找到了以下几行:

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

但在尝试了这个之后,问题就变得很明显了。我在一个非常小的嵌入式系统上运行,我很快就用完了内存(在这个函数的2到3次迭代之后)。检查进程列表,我可以看到一大堆python进程。 现在,我意识到,我可以检查进程列表并杀死所有比我自己有另一个PID的进程——这是我必须做的还是有更好的Python解决方案?在


Tags: the脚本列表进程defsysnotfunction
2条回答

这将使用与生成第一个进程相同的调用来生成一个新的子进程,但它不会停止现有进程(更确切地说:现有进程等待子进程退出)。在

更简单的方法是重构程序,这样就不必重新启动它。你为什么要这么做?在

我将restart函数重写如下,它将在启动新的子进程之前杀死除自身以外的所有python进程:

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    logger.info("RESTARTING SCRIPT")
    # command to extract the PID from all the python processes
    # in the process list
    CMD="/bin/ps ax | grep python | grep -v grep | awk '{ print $1 }'"
    #executing above command and redirecting the stdout int subprocess instance
    p = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
    #reading output into a string
    pidstr = p.communicate()[0]
    #load pidstring into list by breaking at \n
    pidlist = pidstr.split("\n")
    #get pid of this current process
    mypid = str(os.getpid())
    #iterate through list killing all left over python processes other than this one
    for pid in pidlist:
        #find mypid
        if mypid in pid:
            logger.debug("THIS PID "+pid)
        else:
            #kill all others
            logger.debug("KILL "+pid)
            try:
                pidint = int(pid)
                os.kill(pidint, signal.SIGTERM)
            except:
                logger.error("CAN NOT KILL PID: "+pid)


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

不太确定这是否是最好的解决办法,但它对过渡时期有效。。。在

相关问题 更多 >

    热门问题