1
    restartButton = ttk.Button(text = "RESTART?", command = restartProgram)
    restartButton.place(x = 400, y = 100, width = 200, height = 40)

def restartProgram():
    os.execl(sys.executable, os.path.abspath('Game.py'), *sys.argv) 

this is the closest code I could find on restarting a program. However, this code only opened 'Shell' but did not restart the program.

Does anyone know any ways to restart a program by a button click

5
  • 2
    It's usually a better idea to put restart logic inside the program (especially for a game). Relaunching a GUI program may take seconds for the OS and window manager to tear things down and set things up, during which time things will be flashing annoyingly all over the screen (even worse if you've gone full-screen and changed resolution). Notice that most games only do this if they have settings that can't be changed without a restart (like selecting a different graphics or sound engine). Commented May 13, 2018 at 19:50
  • Also, this doesn't necessarily clean up everything—file handles can be inherited over an exec, and actual files or other external resources that you were expecting to be closed by the GC will get left behind instead. Commented May 13, 2018 at 19:51
  • besides, that should work, unless os.path.abspath("Game.py") contains spaces. Commented May 13, 2018 at 19:58
  • @Jean-FrançoisFabre: spaces don't matter when using execl because you directly control each argument. Commented May 13, 2018 at 20:08
  • on my machine it does. S:\>C:\Program: can't open file 'Files\Python36\python.exe': [Errno 2] if second argument contains spaces it fails (windows) Commented May 13, 2018 at 20:25

1 Answer 1

1

Use the following sample program. It will close all the opened files and connections, that could have caused memory issues.
Then it will restart the program.

import os
import sys
import psutil
import logging

def restart_program():
    """Restarts the current program, with file objects and descriptors
       cleanup
    """

    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

    python = sys.executable
    os.execl(python, python, *sys.argv)

Please try the below code. Tested on Ubuntu 18.04.

from Tkinter import *
import os
import sys
import psutil
import logging

def button_click():
    """ handle button click event and output text from entry area"""
    print('hello, submit button is clicked')    
    # do here whatever you want

def restart_program():
    """Restarts the current program, with file objects and descriptors cleanup"""
    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

    python = sys.executable
    os.execl(python, python, *sys.argv)


def create_gui_app(label_title='Hello, How are you?'):
    window = Tk()
    window.title("Welcome to LikeGeeks app")
    lbl = Label(window, text=label_title)
    lbl.grid(column=0, row=0)

    submit_button = Button(window, command=button_click, text="Submit")
    submit_button.grid()
    restart_button = Button(window, command=restart_program, text="Restart")
    restart_button.grid()
    window.mainloop()

if __name__=='__main__':
    if len(sys.argv) > 1:
        create_gui_app(sys.argv[1])
    else:
        create_gui_app('No Argument Supplied!!!')
Sign up to request clarification or add additional context in comments.

6 Comments

that works only if python doesn't contain spaces. I'd do os.execl(python, "python", *sys.argv), works on my windows machine (otherwise it doesn't because of those damn spaces in python path)
OP code should work.
besides, you just copied this code from this question: stackoverflow.com/questions/34582604/…
@Jean-FrançoisFabre: spaces won't matter in this specific case. Spaces only matter when something is trying to split a command line into tokens. This code doesn't do that, and is one of the advantages to using execl over some of the other variations.
@nandal it seems like your code will work, but again it restarted shell and not the program
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.