我怎样才能将我的程序设置为 运行 直到出现错误,这样如果出现错误它会重试?

How can i set my program to run until get an error and so that if it gets an error it will try again?

我有一段代码,会不断作用于数据库,保持更新,但不会出现网络中断等情况,不知为何,程序容易出错。我希望程序每 240 秒 运行 并在出现错误时最多重复该过程 3 次,如果出现错误 3 次,我希望它 return 到它的旧周期,也就是说,每 240 秒,你能帮忙吗?如果您能提供信息,我也将非常感谢,以便我可以在后台制作我的程序运行。

import time


class mysql_connections():
  def ___init__(self):
      .
      .
      .
  def table_query(self):
      .
      .
      .
...
if __name__ == "__main__":
delay = 10
sql = mysql_connections()
while 1:
    try:
        time.sleep(delay)
        sql.table_query()
        delay = 240
    except:
        delay = 10

我试过了,但不太清楚

请参阅这篇文章,了解如何在 Stack Overflow 上提出一个好的问题并提供一个最小的可重现示例:

https://whosebug.com/help/how-to-ask

这将有助于提供答案,因为它允许人们测试确切的问题并为您提供更有针对性的问题。

也就是说,您是否尝试过使用异常处理程序?这可以在脚本不崩溃的情况下捕获错误,例如:

try:
    int('hello')
except:
    print('That didn't work!')

对于您的情况,您可以在脚本开头附近的某处添加:

error_count = 0

然后为您的异常处理程序做:

try:
    # your code here
except:
    error_count += 1

然后在接近尾声的地方:

if error_count == 3:
    # change period to 240 seconds

一般的异常处理程序不被认为是非常 Pythonic 的,如果您知道将抛出的特定错误,最好缩小异常范围,例如 int('hello') 将抛出 ValueError .所以最好写成:

try:
    int('hello')
except ValueError:
    print('That can't be converted to an integer!')

希望对您有所帮助。