Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart python-script from within itself

Tags:

python

I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:

./myscript.py --some-flag setting

From within the program the user can download (using Git) newer versions. If such exists/are downloaded, a button appear that I wish would restart the program with newly compiled contents (including dependencies/imports). Preferably it would also restart it using the contents of sys.argv to keep all the flags as they were.

So what I fail to find/need is a nice restart procedure that kills the current instance of the program and starts a new using the same arguments.

Preferably the solution should work for Windows and Mac as well but it is not essential.

like image 704
deinonychusaur Avatar asked Jul 04 '12 13:07

deinonychusaur


2 Answers

You're looking for os.exec*() family of commands.

To restart your current program with exact the same command line arguments as it was originally run, you could use the following:

os.execv(sys.argv[0], sys.argv) 
like image 65
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 17:09

Ignacio Vazquez-Abrams


I think this is a more elaborate answer, as sometimes you may end up with too many open file objects and descriptors, that can cause memory issues or concurrent connections to a network device.

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) 
like image 37
s3ni0r Avatar answered Sep 16 '22 17:09

s3ni0r