Automatically restart Python program if it is killed

I am running a Python Discord bot. I am importing some modules and some events. At times, it seems like the script is killed for some unknown reason. Maybe due to an error / exception or connection issue? I'm not a Python expert, but I managed to get my bot to work really well, I just don't quite understand how it works under the hood (since the program does nothing but wait for events). Anyway, I would like it to automatically restart after it stops.

I am using Windows 10 and just start my program either by double clicking on it or through pythonw.exe if I don't want that window. What's the best way to check if my program is running (it doesn't have to be instantaneous, it can check every X minutes)? I was thinking about using a batch file or some other Python script, but I have no idea how.

Thank you for your help.

+3


source to share


2 answers


You can write another one python code (B)

to invoke your original python code (A)

one using Popen

from subprocess

. In python code (B)

request a program wait

for python code (A)

. If 'A'

exits with error code

, recall

out B

.

I provide an example for python_code_B.py

import subprocess

while True:
    """However, you should be careful with the '.wait()'"""
    p = subprocess.Popen(['python' 'my_python_code_A.py']).wait()

    """#if your there is an error from running 'my_python_code_A.py', 
    the while loop will be repeated, 
    otherwise the program will break from the loop"""
    if p != 0:
        continue
    else:
        break

      



This generally works well on Unix-based / Unix-like systems. This can fail on some Windows machines that do not correctly return exit codes for programs.

Alternatively, start python_code_B.py

from a "real terminal".

+3


source


for the problem you stated, I prefer to use python subprocess to cause the python script to restart, or use try to block . This might be helpful for you. check this example try the block code:



try:
  import xyz # consider it is not exist or any error code
except:
  pass # go to next line of code to execute

      

+1


source







All Articles