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!!!')
exec, and actual files or other external resources that you were expecting to be closed by the GC will get left behind instead.os.path.abspath("Game.py")contains spaces.execlbecause you directly control each argument.S:\>C:\Program: can't open file 'Files\Python36\python.exe': [Errno 2]if second argument contains spaces it fails (windows)