Python Forum

Full Version: Restarting code from scratch
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've got a program/script that I want it to restart from scratch if an error occurs. The script to restart the code looks like this:

import os
import sys
def divide(a,b):
        try:
            return a/b
        except ZeroDivisionError:
            print("Cannot divide by zero. Restarting. ")
            os.execl(sys.executable, sys.executable, *sys.argv)

a = int(input("Please enter first number. "))
b = int(input("Please enter second number. "))
divide(a,b)
The code runs fine until the restart line is executed; The output looks like this when the code restarts, as expected:
Output:
PS D:\python> python testexit.py Please enter first number. 5 Please enter second number. 0 Cannot divide by zero. Restarting. PS D:\python> Please enter first number.
The problem happens when I tried to re-enter the first number (5) after the code restarted. I get an output that looks like this (line 5):
Output:
PS D:\python> python testexit.py Please enter first number. 5 Please enter second number. 0 Cannot divide by zero. Restarting. PS D:\python> 5lease enter first number.
Powershell then hangs (will not respond to further keyboard input) and I will have to close it and start over again.

Accompanying screenshot below.

Some advice to fix this would be appreciated.

Thanks
It seems to me you are shooting at a tiny problem with heavy guns. To my opinion using "os.execl" for this occasion is not pythonic. On one hand you are right that an error should be fixed at the location where it occurs. So I wondered why I do not like this solution? It is because the error is not really solved.
So instead I propose to catch the error on a level where it can be retried. Like this:
def divide(a,b):
    return a/b
 
while True:
    a = int(input("Please enter first number. "))
    b = int(input("Please enter second number. "))
    try:
        print(divide(a,b))
        break
    except ZeroDivisionError:
        print("Cannot divide by zero. Restarting. ")
I hope you agree with this solution.