You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas read_csv如何设置超时 解决谷歌表格CSV读取卡死问题

问题原因

你遇到的报错来自两个核心问题:

  • func_timeout的args参数接收元组格式的位置参数序列,你写的args=(csv_file)没有在元素后加逗号,在Python里这不是单元素元组,就是字符串本身。字符串是可迭代对象,会被逐字符拆成100多个独立位置参数传给pd.read_csv,才会触发"传入168个位置参数"的错误。
  • 直接传URL给pd.read_csv时,pandas内置的网络请求模块默认没有超时配置,一旦Google Sheets链接异常就会永久阻塞;同时pandas未来版本会强制要求除filepath_or_buffer外的所有参数使用关键字传参,才会弹出FutureWarning。
推荐方案(稳定性最高)

放弃用func-timeout暴力终止线程的思路,改用带原生超时控制的HTTP客户端先拉取CSV内容,再交给pandas解析,从网络层解决挂死问题,完全没有版本兼容问题:

  1. 先安装必要依赖
pip install pandas requests
  1. 可直接运行的代码
import pandas as pd
import requests
from io import StringIO

CSV_TARGET = 'https://docs.google.com/spreadsheets/d/e/XXXX/pub?gid=0&single=true&output=csv'
CONNECT_TIMEOUT = 30

try:
    # 发起带超时的请求,连接/读取超过30秒直接抛出超时异常
    response = requests.get(CSV_TARGET, timeout=CONNECT_TIMEOUT)
    response.raise_for_status() # 遇到404、500等HTTP错误直接抛出异常
    # 将响应文本转为内存文件流传给pandas解析,不会触发传参告警
    df = pd.read_csv(StringIO(response.text))
    print(df)
except requests.exceptions.Timeout:
    print('timeout')
except requests.exceptions.RequestException as e:
    print(f'请求错误: {e}')
except Exception as e:
    print(f'解析错误: {e}')

运行后会直接输出你预期格式的DataFrame,不会有告警,也不会出现永久挂死的问题。

兼容原func-timeout写法的修正版

如果你因为项目依赖限制必须用func-timeout,只需要修正参数传法即可:

from func_timeout import func_timeout, FunctionTimedOut
import pandas as pd

try:
    csv_file = 'https://docs.google.com/spreadsheets/d/e/XXXX/pub?gid=0&single=true&output=csv'
    # 用kwargs传参规避FutureWarning,不需要处理元组格式问题
    df = func_timeout(
        30, 
        pd.read_csv, 
        kwargs={'filepath_or_buffer': csv_file}
    )
    print(df)
except FunctionTimedOut:
    print('timeout')
except Exception as e:
    print(e)

不推荐长期用这个方案:func-timeout是通过线程级抛异常实现中断,在网络IO完全挂死的场景下可能出现连接资源未释放的问题,稳定性不如原生请求超时的方案。

内容的提问来源于stack exchange,提问作者Digital Farmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:27:14