Dealing with EOFError: Ran out of input error from file that is constantly updated

Dealing with EOFError: Ran out of input error from file that is constantly updated

我有以下代码全天频繁加载 pickle 文件:

import pandas as pd

df = pd.read_pickle('data')

有时我会收到以下错误:

EOFError: Ran out of input

我假设当文件正在被不同的程序更新时会发生这种情况。为了解决这个问题,我尝试了以下方法:

import pandas as pd
import time

try:
    df = pd.read_pickle('data')
except:
    time.sleep(0.5)
    df = pd.read_pickle('data)

我得到错误的频率较低,但最终我再次得到它,因为“数据”文件不断更新,每秒不止一次。

有没有一种方法可以使循环在抛出错误之前不断尝试 10 或 20 次?不只是写 10 或 20 个嵌套的尝试和例外?

要回答关于尝试 20 次的问题,您可以使用循环。确保捕获特定的异常,以防抛出不同的错误。

for i in range(20):
    try:
        df = pd.read_pickle('data')
    except EOFError:
        time.sleep(0.5)