Hello everyone, I'm pretty new to python and I have found this code https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program to restart a python program. I have developed a little program and applied this function to it.

By pressing a Button the function resize() is being called which triggers the restart_program() function.

But when I start the programm in a CMD Shell it shuts down but does not come back again.
When I separately try out the short code snippet from Gribouillis it works fine...

I hope the code you'll find below is enough, because I don't want to add the ~1.200 lines of code I've written ...

Thanks in advance!

def resize():
    B = csizeb.get()
    H = csizeh.get()

    try: # Versuche B und H in 'int' umzuwandeln. Falls nicht möglich, zeige allgemeinen Fehler #
        b = int(B)
        h = int(H)
        if 500 <= b <= 2000 and 400 <= h <= 2000: # Eingabewerte prüfen #
            tkinter.messagebox.showinfo("Neustart erforderlich","Programm wird neugestartet!")
            csize = open("csize.txt", "w")
            csize.write(B + "\n")
            csize.write(H)
            csize.close()
            restart_program()
        else:
            tkinter.messagebox.showerror("Hinweis!","Eingabe konnte nicht verarbeitet werden.\n\nBitte wählen Sie eine Größe zwischen 500 x 400 und 2000 x 2000 Pixeln.")
            return
    except:
        tkinter.messagebox.showerror("Eingabe ungültig ...", "Es können nur Zahlen verarbeitet werden!")
        return

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

Recommended Answers

All 5 Replies

Can you add enough code so that we can have the button that calls the resize() function and try it ourselves and reproduce the error ?

Here is the updated code. Additionally for the script to work you have to create a csize.txt and insert two integer numbers into row 0 and row 1.

What's weird is, that now - other than in my program - the script executes the try-Block including the restart command and afterwards also executes the "except"-Block which it shouldn't!?

from tkinter import *
import tkinter.messagebox

root = Tk()

def restart_program():
        """Restarts the current program.
        Note: this function does not return. Any cleanup action (like
        saving data) must be done before calling this function."""
        python = sys.executable
        os.execl(python, python, * sys.argv)

def resize():
    B = csizeb.get()
    H = csizeh.get()
    try:
        b = int(B)
        h = int(H)
        if 500 <= b <= 2000 and 400 <= h <= 2000: # Check new size
            tkinter.messagebox.showinfo("Restart necessary","Programm is being restarted!")
            csize = open("csize.txt", "w")
            csize.write(B + "\n")
            csize.write(H)
            csize.close()
            restart_program()
        else:
            tkinter.messagebox.showerror("Info!","Can not process entered values.\n\nPlease choose size between 500 x 400 to 2000 x 2000 pixels.")
            return
    except:
        tkinter.messagebox.showerror("Entered value failed.", "Only able to process numbers!")
        return

csize = open("csize.txt").readlines()
B = int(csize[0])
H = int(csize[1])

# Button Resize OK #
buttonresize = Button(master=root, text = "OK", command=resize)
buttonresize.grid(row=0, column=5, sticky="sw", padx=3, pady=6)

csizeb = Entry(master=root, width=5)
csizeb.grid(row=0, column=1, sticky="sw", padx=3, pady=6)
csizeb.insert(0,B)

csizeh = Entry(master=root, width=5)
csizeh.grid(row=0, column=3, sticky="se", padx=3, pady=6)
csizeh.insert(0,H)

root.mainloop()

The exception is a NameError. The solution is to add

 import os
 import sys

at the top of the program. Then it works. Notice that a bare

 except:
     ...

is not a good thing because it hides all the exceptions that may occur in the try part. A messagebox saying that something failed is not useful. The user, or the developer needs to know exactly what went wrong, so it is much better to let the exceptions propagate rather than to hide them. You can also use the traceback module in order to transform an exception into a useful message to put in a messagebox!

Oh of course, thank you! Now it works as it should and it even restarts in the IDLE Shell.

But still, when I use this function in my main program, it just won't work ...

But still, when I use this function in my main program, it just won't work

Add temporarily a raise statement in your main program

except:
    raise
    ...

it will prevent the exception to be caught, and the exception traceback will tell you more about the error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.