Search code examples
pythonrestart

Python: How do I make a restart() function?


I'm wondering if I could make something similar to the quit command but instead of ending the script it restarts it from line 1.

Example:

def restart():
   #Something that would repeat the whole script.

answer = input("Test")
if answer = "Restart":
    restart()

Solution

  • As said, one way to do this is to make an infinite loop, using while True: or something else.

    But if you want to make it into a function you have to do this:

    import os
    import sys
    
    def restart():
        os.execl(sys.executable, sys.executable, *sys.argv)
    

    For example:

    import time
    import os
    import sys
    
    def restart():
        os.execl(sys.executable, sys.executable, *sys.argv)
    
    print("Test")
    time.sleep(1)
    restart()