-1

I have a script of a bot deployed on azure that has to be always running. it's a python bot that tracks Twitter mentions in real time by opening a stream listener.

The script fails every once in a while for reasons not directly related to the script (timeouts, connection errors, etc). After searching for answers around here I found this piece of code as the best workaround for restarting the script every time it fails.

#!/usr/bin/env python3.7
import os
def run_bot():
    while True:
        try:
            os.system("test_bot.py  start")
        except:
            pass
if __name__ == "__main__":
    run_bot()

I am logging all error messages to learn the reasons why it fails but I think there just be a better way to achieve the same, I would very much appreciate some hints.

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
  • Stack Overflow is not intended to replace existing documentation and tutorials; this site is not a research or coding service. Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). – Prune Dec 03 '20 at 20:18

1 Answers1

0

So this is wrong way to run a script, you are running it in while loop forever.

A better way is either to schedule your main script in a cron job: Execute Python script via crontab

You can schedule this job to run every min, or hour or a specific time of the day, up to you.

If you wish to run something always, like a system monitor. Then you can run that part inside a while True loop that is fine. Like a loop which checks temperature every 5 secs writes to a file and sleep for 5 secs.

sample sudo code for the script: prog.py

while True:
    log_temp()
    time.sleep(5secs)

But if the script fails then schedule something to restart the script. Dont start the script inside another while loop.

Something like this: https://unix.stackexchange.com/questions/107939/how-to-restart-the-python-script-automatically-if-it-is-killed-or-dies

Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
  • Thanks for your answer, I should have added that the script has to be always running, it's a python bot that tracks twitter mentions in realtime by opening a stream listener. Every time it fails It's restarted in the same loop – Francisco Arcila Dec 03 '20 at 21:37