How to restart python script?

54 Views Asked by At

I'm new to Python and I know that this might be considered as duplicate, because I have searched for solution for this problem but unfortunately nothing seems to be working for me as expected. I would like to restart script, which means to re-run running process or create separate one and kill the previous.

Currently I'm running script with Python 3.11.2, I have tried os.execv(sys.executeable, ['python'] + sys.argv) but for me this works just like exit(), it terminates the script and won't start it again. I have got closer by using os.system("py "+sys.argv[0]) but here is another problem and that is it will create new process but that seems to be dependent on previous one, so I cannot call simply exit() afterwards to stop it like in my code.

import os
import sys
from multiprocessing import Process 

def run():
    print("Running tests...")


def restart():
    print("Restarting...")
    os.system("python " + sys.argv[0])
    exit()

textInput = "N"
print("Starting...")   
while textInput.startswith("N"):
    run()
    textInput = input("Restart ? (Y/N)")
    if textInput.startswith("Y"):
        restart()

1

There are 1 best solutions below

7
Barmar On BEST ANSWER

You're calling os.execv() incorrectly, you can't concatenate a string and a list. You can concatenate two lists, though, so you need to wrap a list around the executable name.

os.execv(sys.executable, [sys.executable] + sys.argv)

You can also use os.execl() and spread sys.argv into separate arguments.

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

Transcript:

$ python testrestart.py 
Starting...
Running tests...
Restart ? (Y/N)Y
Restarting...
Starting...
Running tests...
Restart ? (Y/N)Y
Restarting...
Starting...
Running tests...
Restart ? (Y/N)N
Running tests...
Restart ? (Y/N)N
Running tests...
Restart ? (Y/N)Q