close

How to make a script automatically restart itself?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to make a script automatically restart itself in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to make a script automatically restart itself?

  1. 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:

  2. 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:

Method 1

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.

Method 2

I use terminal on my Mac to re-start some of my python scripts with the function below.

import subprocess  
def run_again(cmd):
    subprocess.call(["bash", "-c", "source ~/.profile; " + cmd])  

Note: Don’t forget the space character after “profile;” or the function may fail silently!

Then at the bottom of my script to be re-started:

if some_condition:  
    run_again("python my_script.py %s" % my_new_arguments)  

For the original question about the cheese script:

if var != 'yes':  
    run_again("python my_cheese_script.py")  

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read