Restart Python-Script from Within Itself

Restart python-script from within itself

You're looking for os.exec*() family of commands.

To restart your current program with exact the same command line arguments as it was originally run, you could use the following:

os.execv(sys.argv[0], sys.argv)

How to make a script automatically restart itself?

It depends on what you mean by "restart itself." If you just want to continuously execute the same code, you can wrap it in a function, then call it from within a while True loop, such as:

>>> def like_cheese():
... var = input("Hi! I like cheese! Do you like cheese?").lower() # Corrected the call to `.lower`.
... if var == "yes":
... print("That's awesome!")
...
>>> while True:
... like_cheese()
...
Hi! I like cheese! Do you like cheese?yes
That's awesome!
Hi! I like cheese! Do you like cheese?yes
That's awesome!

If you want to actually restart the script you can execute the script again, replacing the current process with the new one by doing the following:

#! /bin/env python3
import os
import sys

def like_cheese():
var = input("Hi! I like cheese! Do you like cheese?").lower()
if var == "yes":
print("That's awesome!")

if __name__ == '__main__':
like_cheese()
os.execv(__file__, sys.argv) # Run a new iteration of the current script, providing any command line args from the current iteration.

This will continuously re-run the script, providing the command line arguments from the current version to the new version. A more detailed discussion of this method can be found in the post "Restarting a Python Script Within Itself" by Petr Zemek.

One item that this article notes is:

If you use the solution above, please bear in mind that the exec*()
functions cause the current process to be replaced immediately,
without flushing opened file objects. Therefore, if you have any
opened files at the time of restarting the script, you should flush
them using f.flush() or os.fsync(fd) before calling an exec*()
function.

Python: Restart script and exit it after function does not work

I have been able to answer this question myself in the meantime.

I have done the following:

game_logic() is started via another py file (main.py).

At the restart which is executed within the game_logic() with os.system('main.py'), the current py file containing game_logic() is not terminated.

So if the main.py file is restarted, I have the file containing the game_logic() terminate afterwards.

It looks like this:

import os
import sys

while (res := input("Do you want to play again [1] oder exit[2]?\n").lower()) not in {"1", "2"}:
pass
if res == "1":
os.system('main.py')
exit()
else:
exit()

How to restart a python script after it finishes

You could wrap your script in a

while True:
...

block, or with a bash script:

while true ; do
yourpythonscript.py
done

Automatically restart a Python program if it's killed

You can write another python code (B) to call your original python code (A) using Popen from subprocess. In python code (B), ask the program to wait for your python code (A). If 'A' exits with an error code, recall it from B.

I provide an example for python_code_B.py

import subprocess

filename = 'my_python_code_A.py'
while True:
"""However, you should be careful with the '.wait()'"""
p = subprocess.Popen('python '+filename, shell=True).wait()

"""#if your there is an error from running 'my_python_code_A.py',
the while loop will be repeated,
otherwise the program will break from the loop"""
if p != 0:
continue
else:
break

This will generally work well on Unix / Windows systems. Tested on Win7/10 with latest code update.

Also, please run python_code_B.py from a 'real terminal' which means running from a command prompt or terminal, and not in IDLE.



Related Topics



Leave a reply



Submit