![](/img/trans.png)
[英]How can I make it so that my program asks again for an input after encountering the 'try' and 'except' part of my code?
[英]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次,我想讓它回到原來的時期,也就是每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://stackoverflow.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!')
希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.