有没有办法在 pandas read_sql 函数中设置超时?

Is there any way to put timeout in pandas read_sql function?

我在 python 代码中通过 ODBC 连接连接到 DB2 服务器。 DB2 服务器重新启动以进行维护或在 运行 特定服务器端任务时断开我的连接,一天发生 1 或 2 次。那时,如果我的代码已经开始执行 pandas read_sql 函数来获取查询结果,即使服务器在 1 小时后启动,它也会进入无限等待状态。

我想在 read_sql 的执行中设置一个超时,每当发生超时时,我想刷新与 DB2 服务器的连接,以便在继续查询之前再次建立新的连接。

我已经尝试制作一个 while 循环并从 DB2 中提取数据块而不是一次提取整个结果,但问题是如果 DB2 在提取块时断开连接 python 代码仍然会进入无限等待。

chunk_size = 1000    
offset = 0
while True:
        sql = "SELECT * FROM table_name limit %d offset %d" % (chunk_size,offset)
        df = pd.read_sql(sql, conn)
        df.index += (offset+1)
        offset += chunk_size
        sys.stdout.write('.')
        sys.stdout.flush()
        if df.shape[0] < chunk_size:
            break

如果 sql 执行时间超过 3 分钟,我需要 read_sql 抛出一些异常或 return 一个值。如果发生这种情况,我需要连接到 DB2 才能刷新。

您可以使用包 func-timeout。您可以通过 pip 安装如下:

pip install func-timeout

因此,例如,如果您有一个函数“doit('arg1', 'arg2')”,您希望将其限制为 运行 5 秒,使用 func_timeout 您可以像这样称呼它:

from func_timeout import func_timeout, FunctionTimedOut

try:
  doitReturnValue = func_timeout(5, doit, args=(‘arg1’, ‘arg2’))
except FunctionTimedOut:
  print ( “doit(‘arg1’, ‘arg2’) could not complete within 5 seconds, hence terminated.\n”)
except Exception as e:
  # Handle any exceptions that doit might raise here