I'm experiencing some unexpected behavior with os.execl on Windows with Python 3.3.2 (this may well apply in other places, but this is the only environment I've attempted this in). My goal in this example is to be able to restart a currently running program on KeyboardInterrupt. My code:
import os
import sys
import time
def main():
print("Welcome.")
while True:
try:
print("Hello.")
time.sleep(10)
except KeyboardInterrupt:
break
args = sys.argv
args[0] = '"' + args[0] + '"'
# This should restart the program.
os.execl(sys.executable, sys.executable, * args)
if __name__ == '__main__':
main()
When I run my program by simply double clicking on the .py file, and then keyboard interrupt, everything goes exactly as expected. My program restarts, and I see a second Welcome message. I can do this any number of times without issue.
When I run via command line (either by typing python myprog.py or simply myprog.py), some funky things seem to happen. Upon issuing a KeyboardInterrupt, the program seems to stop without restarting. When I look in my task manager, I curiously still see a python.exe running. If I run my program again from the command line, I immedieately see:
Welcome
Hello
Welcome
Hello
If I KeyboardInterrupt out of this again, I now see two rogue python.exe processes sitting in my task manager. Sure enough if I run a third time from the command line, I now see three Welcome/Hello messages.
Would love to know if this is the expected behavior, or if there's something else I need to be doing to make running from the command line work in this situation?