简体   繁体   中英

Restart python script

I have a script that collects data from the streaming API. I'm getting an error at random that I believe it's coming from twitter's end for whatever reason. It doesn't happen at specific time, I've been seen it as early as 10 minutes after running my script, and other times after 2 hours.

My question is how do I create another script (outside the running one) that can catch if it terminated with an error, then restart after a delay.

I did some searching and most were related to using bash on linux, I'm on windows. Other suggestions were to use Windows Task Scheduler but that can only be set for a known time.

I came across the following code:

import os, sys, time

def main():  
    print "AutoRes is starting"
    executable = sys.executable
    args = sys.argv[:]
    args.insert(0, sys.executable)

    time.sleep(1)
    print "Respawning"
    os.execvp(executable, args)

if __name__ == "__main__":  
    main()

If I'm not mistaken that runs inside the code correct? Issue with that is my script is currently collecting data and I can't terminate to edit.

How about this?

from os import system
from time import sleep

while True: #manually terminate when you want to stop streaming
    system('python streamer.py')
    sleep(300) #sleep for 5 minutes

In the meanwhile, when something goes wrong in streamer.py , end it from there by invoking sys.exit(1)

Make sure this and streamer.py are in the same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM