在 python 的 while 循环中构建重试机制

Building a retry mechanism in a while loop in python

while true:
    ticker = binance.fetch_ticker("BTC/USDT")
    current_price = ticker['last']
function_A(current_price)

我有一个 while 循环,让 运行 每秒检查比特币的当前价格。然后我还有一个将 current_price 作为输入的函数。

不过,我偶尔会

"requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))"

所以我尝试使用 try, except 在出现此错误时建立重试机制。 我试过这个:

while true:
    try_count = 10
    while try_count > 0:
        try:
            ticker = binance.fetch_ticker("BTC/USDT")
            current_price = ticker['last']
            try_count = 0
            break
        except (requests.ConnectionError, requests.ReadTimeout) as error:
            print(error, " detected. Trying again...")
            try_count -= 1
    function_A(current_price)

问题是,如果我这样做,当我将它作为输入插入最后一行的 function_A 时,current_price 最终未定义。我该如何解决这个机制?

您可能想要探索有助于重试函数的退避库。 https://pypi.org/project/backoff/

您可以在 fetch_ticker 函数上添加一个 backoff 装饰器,它应该在遇到 RequestException 错误时重试。

代码应该类似于

@backoff.on_exception(backoff.expo, requests.exceptions.RequestException)
def fetch_ticker(ticker):
    # binance.fetch_ticker

在第二个 while 循环之外的范围内定义 current_price 可以防止 current_price 在调用 function_A.

时有时未定义的问题
while True:
    current_price = None
    try_count = 10
    while try_count > 0:
        try:
            ticker = binance.fetch_ticker("BTC/USDT")
            current_price = ticker['last']
            try_count = 0
            break
        except (requests.ConnectionError, requests.ReadTimeout) as error:
            print(error, " detected. Trying again...")
            try_count -= 1
    if current_price is not None:
        function_A(current_price)