简体   繁体   English

如何从主 python 脚本重新启动正在运行的 python 脚本?

[英]How to restart a running python script from a main python script?

I know that我知道

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

restarts the current running python script.重新启动当前正在运行的 python 脚本。 But how do I restart another running python script from a main running python script?但是,如何从主要运行的 python 脚本重新启动另一个正在运行的 python 脚本?

You can do it the following way:您可以通过以下方式进行操作:

master process - main.py:主进程 - main.py:

import time
import subprocess as sp


def restart_subprocess(sub_process, commands):
    sub_process.kill()  # kill old one process
    time.sleep(1)
    print("Restarted")
    return sp.Popen(commands)  # start a new one, hereby restart it


if __name__ == "__main__":
    while True:
        x = sp.Popen(["python", "sub.py"],)  # start subprocess
        time.sleep(2)  # show that it works
        y = restart_subprocess(x, ["python", "sub.py"])  # restart it, actually make a new one
        if y.wait(10) == 100:  # wait at least 10 seconds ore receive exit code from child process and check it
            print("Finish!")
            break

Note that if you are on Linux you need to specify python version ["python3", "sub.py"]请注意,如果您使用的是 Linux,则需要指定 python 版本["python3", "sub.py"]

child process - sub.py:子进程 - sub.py:

import time
import sys

if __name__ == "__main__":
    for i in range(5):
        print(i)
        time.sleep(1)
    sys.exit(100)

Hope it helped, feel free to ask questions.希望对您有所帮助,欢迎提问。

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

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