Search code examples
pythonexitrestartsysos.system

Python: Restart script and exit it after function does not work


After a run, the user is asked whether he wants to end the programme [with sys.exit()] or restart it [os.system('main.py')].
If he restarts the programme, the programme will run through until he can decide again whether to restart or exit.
If the user then wants to end the programme, however, this is not possible, the programme is restarted anyway.
Also quit() or exit() do not work.

This is the prompt that asks the user to restart or quit:

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')
else:
    end_game = True  # Stops the loop, but is not necessary
    print("Sys.exit game")
    sys.exit(0)

When I use subprocess.call(sys.executable + ' "' + os.path.realpath(__file__) + '"'),
exiting the program works, but the program is not really restarted [variables set to 0 at the beginning are not at 0].

Small note, the reboot will restart another py file (main.py), which is the main file, with the following content:

class main:
    game_logic()

if __name__ == '__main__':
    main()

game_logic() is the function from the other Py file in which the query for restarting and exiting is.


Solution

  • 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()