简体   繁体   English

Python脚本无法正常自行重启

[英]Python script doesn't restart itself properly

I have a Python script and I want to have it restart itself. 我有一个Python脚本,我想让它重新启动。 I found the following lines Googling around: 我发现以下几行搜索内容:

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)

but problems became apparent right after trying this out. 但是尝试一下后问题变得显而易见。 I'm running on a really small embedded system and I ran out of memory really quick (after 2 or three iterations of this function). 我正在一个非常小的嵌入式系统上运行,并且我很快就耗尽了内存(此函数经过2或3次迭代)。 Checking the process list, I can see a whole bunch of python processes. 查看进程列表,我可以看到一大堆python进程。 Now, I realize, I could check the process list and kill all processes that have another PID than myself - is this what I have to do or is there a better Python solution? 现在,我意识到,我可以检查进程列表并杀死具有除我以外的其他PID的所有进程-这是我必须要做的,还是有更好的Python解决方案?

This spawns a new child process using the same invocation that was used to spawn the first process, but it does not stop the existing process (more precisely: the existing process waits for the child to exit). 这将使用与产生第一个进程相同的调用来产生一个新的子进程,但不会停止现有进程(更确切地说:现有进程等待子进程退出)。

The easier way would be to refactor your program so you don't have to restart it. 比较简单的方法是重构程序,这样就不必重新启动它。 Why do you need to do this? 为什么需要这样做?

I rewrote my restart function as follows, it will kill every python process other than itself before launching the new sub process: 我重写了重新启动函数,如下所示,它将在启动新的子进程之前杀死除自身以外的所有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)

Not exactly sure if this is the best solution but it works for the interim anyways... 不确定是否这是最好的解决方案,但是无论如何它都适用于临时方案...

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

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