I have a Python program that runs a cell model continuously. when I press “A” or “B” certain functions are called – cell divide, etc. when the “esc” key is pressed the simulation exits. Is there a way for the program to exit and then restart itself when “esc” is pressed?
Share
Yes. This is probably what you want
So when you want the program to restart itself, just call its
sys.argv[0]usingos.system()and immediately callexit(some_return_code_here)(zero means ‘no error’). You might want to pass an extra argument so it knows it’s a restarted instance, but are by no means required to do so; I did so above to prevent endless loop. If you have other mechanisms to prevent endless loops, then use those.Please also note: for the above code, you need to run the program directly;
python test.pydid not do the trick for me (for obvious reasons). Also, above will probably work only under UNIX systems.Note, also, that
system()is blocking. If you need the original program to complete shutdown upon launching new program, easiest way would be to send the new one into background (thus “unblocking”system()). Just modify the line like this:Note the “&” which tells the shell to send the new process into background.