user8393645
user8393645

Reputation: 110

Automatically restarting Python Script on Exception

I have a really complicated Python script going on, sometimes it just gets an error, and the only way to debug this, is restarting it, because everything else would make no sense and the error would come back in no time (I already tried a lot of things, so please dont concentrate on that)

I want a .bat script (im on Windows unfortunately) that restarts my python script, whenever it ends. Another python script is also fine.

How can I do that? Thanks in advance

Upvotes: 0

Views: 1165

Answers (1)

Hariom Singh
Hariom Singh

Reputation: 3632

set env=python.exe  
tasklist /FI "IMAGENAME eq python.exe" 2>NUL | find /I /N "python.exe">NUL if "%ERRORLEVEL%"!="0(
   start python script.py
)

Other way from python to execute python

import subprocess
from subprocess import call

def processExists(processname):
    tlcall = 'TASKLIST', '/FI', 'imagename eq %s' % processname
    # shell=True hides the shell window, stdout to PIPE enables
    # communicate() to get the tasklist command result
    tlproc = subprocess.Popen(tlcall, shell=True, stdout=subprocess.PIPE)
    # trimming it to the actual lines with information
    tlout = tlproc.communicate()[0].strip().split('\r\n')
    # if TASKLIST returns single line without processname: it's not running
    if len(tlout) > 1 and processname in tlout[-1]:
        print('process "%s" is running!' % processname)
        return True
    else:
        print(tlout[0])
        print('process "%s" is NOT running!' % processname)
        return False



if not processExists('python.exe')
   call(["python", "your_file.py"])

Upvotes: 1

Related Questions