Python restart program

claudio26 picture claudio26 · Jan 6, 2018 · Viewed 34.1k times · Source

I made a program that asks you at the end for a restart.

I import os and used os.execl(sys.executable, sys.executable, * sys.argv) but nothing happened, why?

Here's the code:

restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
    os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
    print("\nThe program will be closed...")
    sys.exit(0)

Answer

SangminKim picture SangminKim · Jan 6, 2018
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 programm will me 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 something like python XX.py arg1 arg2.