0

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.

I have tried subprocess and execv (os.execv(sys.executable, ['python'] + sys.argv)), 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.

Any suggestions? Thanks for your help!

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()
mkj
  • 2,761
  • 5
  • 24
  • 28
NJC
  • 43
  • 1
  • 8

1 Answers1

0

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

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...")

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.

Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
Blackbeard
  • 107
  • 3
  • Thank's for the response! The problem I'm having is not with script that is not shown, but rather with the code that is posted. It turns out that it works fine when I double clock on the script to run it in Windows, however when I type "python myscript.py" from the command line it does not work. No current issues in Linux either. – NJC Oct 16 '16 at 16:47