Self Restarting a Python Script
<p>I have created a watchdog timer for my script (Python 3), which allows me to halt execution if anything goes wrong (not shown in code below). However, I would like to have the ability to restart the script automatically using only Python (no external scripts). The code needs to be cross platform compatible.</p>

<p>I have tried subprocess and execv (<code>os.execv(sys.executable, ['python'] + sys.argv)</code>), however I am seeing very weird functionality on Windows. I open the command line, and run the script ("python myscript.py"). The script stops but does not exit (verified through Task Manager), and it will not restart itself unless I press enter twice. I would like it to work automatically.</p>

<p>Any suggestions? Thanks for your help!</p>

<pre><code>import threading
import time
import subprocess
import os
import sys

if __name__ == '__main__':
    print("Starting thread list: " + str(threading.enumerate()))

    for _ in range(3):
        time.sleep(1)
        print("Sleeping")

    ''' Attempt 1 with subprocess.Popen '''
    # child = subprocess.Popen(['python',__file__], shell=True)

    ''' Attempt 2 with os.execv '''
    args = sys.argv[:]
    args.insert(0, sys.executable)
    if sys.platform == 'win32':
        args = ['"%s"' % arg for arg in args]
    os.execv(sys.executable, args)

    sys.exit()
</code></pre>

<p>Sounds like you are using threading in your original script, which explains why your can't break your original script when simply pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>. In that case, you might want to add a KeyboardInterrupt exception to your script, like this:</p>

<pre><code>from time import sleep
def interrupt_this()
    try:
         while True:
             sleep(0.02)
    except KeyboardInterrupt as ex:
         # handle all exit procedures and data cleaning
         print("[*] Handling all exit procedures...")
</code></pre>

<p>After this, you should be able to automatically restart your relevant procedure (even from within the script itself, without any external scripts). Anyway, it's a bit hard to know without seeing the relevant script, so maybe I can be of more help if you share some of it.</p>

python restart unattended-processing