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.
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)
Is there a way to rerun a python program from within the same program?
You can create a function of the game and run it, like this:
def game():
print('GAME STUFF')
active = True
while active:
game()
restart = input("\n Do you want to restart the program? [y/n] > ")
if restart.lower() == "n":
active = False
Here you create a game loop that calls your function game and when finished if player doesn't want to continue it can end the game, and it ends game loop.
How can i make the program to rerun itself in python?
Loop over that code and break
when you want to stop repeating:
while True: # Will start repeating here
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again != 'Y':
print("OK!! Exiting")
break # break to leave the loop
# It will loop automatically back to the top otherwise
Python restart program
import os
import sys
restart = input("\nDo you want to restart the program? [y/n] > ")
if restart == "y":
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
print("\nThe program will be closed...")
sys.exit(0)
os.execl(path, arg0, arg1, ...)
sys.executable
: python executeable
os.path.abspath(__file__)
: the python code file you are running.
*sys.argv
: remaining argument
It will execute the program again like python XX.py arg1 arg2
.
Related Topics
Tkinter Ttk Treeview How to Set Fixed Width Why It Change With Number of Column
How to Avoid Last Comma in Python Loop
Python: Pickle.Load() Raising Eoferror
Python: How to Calculate the Sum of Numbers from a File
How to Iterate Through Cur.Fetchall() in Python
Python-Compare Two String Columns in Same Dataframe, Return Matching Result
What Is the Most Efficient Way to Sum a Dict With Multiple Keys by One Key
Python Not Working in the Command Line of Git Bash
Iterating Over Every Two Elements in a List
Formal and Actual Parameters in a Function in Python
Pandas - Drop Last Column of Dataframe
Conversion of String to Upper Case Without Inbuilt Methods
Discord.Py Show Who Invited a User
Pandas: Calculate Total Percent Difference Between Two Data Frames
Selenium - Iterating Through Groups of Elements - Python
Pyside - Pyqt:How to Make Set Qtablewidget Column Width as Proportion of the Available Space
Turn the Column Headers into the First Row and Row Headers into the First Column in Pandas Dataframe
How to Extract the Entire Row and Columns When Condition Met in Numpy Array