Skip to content Skip to sidebar Skip to footer

Python Help - Need The Ability To Restart The Script When It Hangs Or Automatically Set A Timer

I currently have a python script that does exactly what I need it to do, however every now and then the script will hang and the only way to restart it is by killing the script and

Solution 1:

Feel free to pay me if you want, although it is by no means necessary.

Here:

import time
import threading
import os

def restart():
    time.sleep(50)
    os.execv('/full/path/to/this/script', ['second argument', 'third argument'])

def main():
    t = threading.Thread(target=restart, args=(), name='reset')
    t.start()
    # ... The rest of your code.

If you have any buffers open that you care about (such as stdout) you'll want to flush them right before the call to execv up there.

I haven't tested this code, because I don't have a python interpreter handy at the moment, but I'd be surprised if it didn't work. That call to execv replaces the current context, so you don't get an increasingly deep hierarchy of child processes. All I'm doing, in case you're curious and want to know what magic phrase to google, is setting a "timer interrupt handler". For the pedants, no, I recognize this thing isn't directly handling any interrupts.

The numeric argument to sleep is in seconds. I would simply request that you not use my code in malware, unless it is for research purposes. I'm particular that way.

edit: Additionally, a lot of it was taken from here.


Post a Comment for "Python Help - Need The Ability To Restart The Script When It Hangs Or Automatically Set A Timer"