Last Update: 24.09.2007. By kerim in python
I wrote a small script that allows for an application to restart. Perhaps it is usefull for others. There are several use cases like “autoupdating” or changes in preferences in the program that require restarts.
Basically it is very easy to do such things and there are several ways to implement them. I wanted to use an “all python” method. The only thing i do is to indirectly start the application via a small starter program that waits for the app to end and analyzes the return code. Depending on that code it starts the app again or not. It’s the same mechanism as for example eclipse uses. In the end the only thing You have to do is to define the return codes and the implications of these codes. For example depending on the code you might have to wait for a while before restarting, or you might do some cleanups etc.
Here is the simple code (99 is the code for “Restart”, 0 for “all ok”):
The short version:
import os
pythonPath='C:\Python25\python'
argList = []
argList.append('PUT_PYTHON_EXECUTABLE_HERE')
argList.append('PUT_PYTHON_APP_HERE')
argList.append(PUT_PARAMETERS_FOR_APP_HERE_AS_LIST)
# Run subprocess
exitSignal= os.spawnv(os.P_WAIT, pythonPath, argList)
if exitSignal == 99:
exitSignal= os.spawnv(os.P_WAIT, pythonPath, argList)
A longer version with better documentation and a test case:
import os
"""
path to the python environment,
"""
pythonPath='C:\Python25\python'
"""
Create parameter list
First parameter must be the python excecutable
Second parameter is the python program to start
Third Parameter is a list of arguments for the python program
"""
argList = []
argList.append('python.exe')
argList.append('C:\Programmierung\workspace\pyteststuff\src\Exiter.py')
#ATTENTION: Here you insert the arguments for the app, 'restart' is just for testing
argList.append('restart')
print "Parameters:",argList
# Fire it up
exitSignal= os.spawnv(os.P_WAIT, pythonPath, argList)
print 'Resturn code:',exitSignal
if exitSignal == 99:
print 'Restarting'
# this time we dont want to restart , so we remove the argument for that
argList.remove('restart')
argList.append('normal')
print "Parameters:",argList
exitSignal= os.spawnv(os.P_WAIT, pythonPath, argList)
print 'Resturn code:',exitSignal
In order to test it use the following snipplet of code.
import os, sys
def quit(mode):
if mode=='restart':
print"Quit called: restarting wished"
os._exit(99)
else:
print"Quit called: no restart"
os._exit(0)
if __name__ == '__main__':
"""
for testing we need at least a parameter that tells us
if we should restart
"""
paramlength=len(sys.argv)
if paramlength<2:
os._exit(0)
mode = sys.argv[1]
quit(mode)
I think it’s pretty self explanatory what happes here. This app (second script) is called with a parameter telling it either to restart or not. It immediately exits again with a return code corresponing to either “restart” or “ok”. Of course you can define those values as you like.