Search code examples
pythonrestartpi

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. But how do I restart another running python script from a main running python script?


Solution

  • You can do it the following way:

    master process - 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"]

    child process - 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.