繁体   English   中英

Python脚本无法正常自行重启

[英]Python script doesn't restart itself properly

我有一个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解决方案?

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

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

我重写了重新启动函数,如下所示,它将在启动新的子进程之前杀死除自身以外的所有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)

不确定是否这是最好的解决方案,但是无论如何它都适用于临时方案...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM