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 usingf.flush()
oros.fsync(fd)
before calling anexec*()
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
Python Requests.Get() Returns Improperly Decoded Text Instead of Utf-8
What Does "Typeerror 'Xxx' Object Is Not Callable" Means
<Django Object > Is Not JSON Serializable
Pandas - Convert Strings to Time Without Date
Print Statement Inside of Input Returns with a "None"
Why Can't Environmental Variables Set in Python Persist
Working with Tiffs (Import, Export) in Python Using Numpy
Filter a Pandas Dataframe Using Values from a Dict
How to Generate a List of Consecutive Numbers
Uploading Multiple Files with Flask
General Unicode/Utf-8 Support for CSV Files in Python 2.6
How to Escape Curly-Brackets in F-Strings
How Come a File Doesn't Get Written Until I Stop the Program
Django Query That Get Most Recent Objects from Different Categories
Calling Dot Products and Linear Algebra Operations in Cython