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

Github Actions中Python脚本连接MySQL遇AttributeError: __enter__错误

问题:Github Actions运行爬虫连接MySQL时出现AttributeError: enter

我有一个本地可正常运行的网络爬虫,会将数据存入托管在filess.io的MySQL数据库中。尝试通过Github Actions设置定时任务持续运行它时,在以下代码处执行失败:

try:
    with connect(
        host=DB_HOST,
        user=DB_USER,
        password=DB_PASSWORD,
        database=DB_DATABASE,
        port=DB_PORT
    ) as connection:
        print(connection)

报错信息如下:

0s
Run python main.py
Traceback (most recent call last):
  File "myscript.py", line 66, in <module>
    with connect(
AttributeError: __enter__
Error: Process completed with exit code 1.

我已在Github中配置Secrets,代码中通过以下片段读取环境变量无报错:

try:
    DB_HOST=os.environ["DB_HOST"]
    DB_USER=os.environ["DB_USER"]
    DB_PASSWORD=os.environ["DB_PASSWORD"]
    DB_DATABASE=os.environ["DB_DATABASE"]
    DB_PORT=os.environ["DB_PORT"]

该脚本在本地通过.env文件存储密钥可正常运行,我已反复核对Github Secrets配置,也验证过本地运行无问题。尝试打印Secrets内容但被系统隐藏,查询得知__enter__错误与属性问题相关,但无法定位具体原因。核心困惑是本地正常但Github Actions运行出错,怀疑是Github配置问题,寻求排查思路。

补充Github Actions工作流代码:

name: Manual workflow
on: [workflow_dispatch]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:

      - name: checkout repo content
        uses: actions/checkout@v2 # checkout the repository content to github runner

      - name: setup python
        uses: actions/setup-python@v4
        with:
          python-version: '3.9' # install the python version needed

      - name: install python packages
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: execute py script # run main.py
        env:
          DB_HOST: ${{ secrets.DB_HOST }}
          DB_USER: ${{ secrets.DB_USER }}
          DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
          DB_DATABASE: ${{ secrets.DB_DATABASE }}
          DB_PORT: ${{ secrets.DB_PORT }}
        run: python main.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:40:24