如何在ubuntu-latest中升级Python的sqlite3至3.38及以上版本?
问题描述
我创建了一个GitHub Actions工作流,用于执行SQL查询,其中使用了SQLite的箭头操作符(-> 和 ->>)处理JSON数据,这要求SQLite版本≥3.38.0。
在windows-latest和macos-latest环境中该工作流可正常运行,因为这些环境中Python 3.11内置的SQLite版本≥3.38。
但在ubuntu-latest环境中遇到问题,其默认SQLite版本为3.37,我需要确保Python使用最新版本的SQLite。
我尝试通过sudo apt -y install sqlite3 libsqlite3-dev命令安装,但无法替换Python中的sqlite3版本,得到提示:
libsqlite3-dev is already the newest version (3.37.2-2ubuntu0.3). sqlite3 is already the newest version (3.37.2-2ubuntu0.3).
参考的GitHub工作流配置如下:
name: 'tests' on: push: branches: - 'testing' jobs: test: name: Test runs-on: ${{ matrix.os }} strategy: matrix: os: ['macos-latest', 'windows-latest', 'ubuntu-latest'] steps: - uses: actions/checkout@v3 - name: Install Latest sqlite3 version on non-windows platform if: ${{ matrix.os == 'ubuntu-latest' }} run: | bash ./.github/scripts/install-sqlite.sh - name: Set up Python 3.11 uses: actions/setup-python@v3 with: python-version: "3.11" - name: Install dependencies run: | python -m pip install --upgrade pip pip install poetry poetry install - name: Smoke Test run: pytest __test__/test_smoke
我甚至尝试从源码安装SQLite,执行sqlite --version显示版本已更新,但Python中的sqlite3版本仍未改变。
请问如何在ubuntu-latest环境中将Python的sqlite3版本从3.37升级至3.38及以上?
解决方案
在Ubuntu环境中,Python内置的sqlite3模块是静态链接到系统SQLite库的,直接更新系统SQLite不会改变Python使用的版本。以下是两种可行的解决方法:
方法一:编译新版Python并链接最新SQLite
- 编译安装最新版SQLite到自定义目录:
# 下载并解压SQLite源码(可替换为最新版本号) wget https://www.sqlite.org/2024/sqlite-autoconf-3450300.tar.gz tar xzf sqlite-autoconf-3450300.tar.gz cd sqlite-autoconf-3450300 # 配置安装路径并编译安装 ./configure --prefix=/usr/local/sqlite3 make sudo make install
- 设置环境变量,让Python编译时优先使用新版SQLite:
export LDFLAGS="-L/usr/local/sqlite3/lib" export CPPFLAGS="-I/usr/local/sqlite3/include" export LD_LIBRARY_PATH="/usr/local/sqlite3/lib:$LD_LIBRARY_PATH"
- 编译安装Python 3.11:
# 下载并解压Python 3.11源码(可替换为对应版本号) wget https://www.python.org/ftp/python/3.11.9/Python-3.11.9.tgz tar xzf Python-3.11.9.tgz cd Python-3.11.9 # 配置编译选项并安装 ./configure --enable-optimizations make sudo make altinstall
- 在GitHub Actions后续步骤中使用编译后的
python3.11命令执行测试。
方法二:使用pysqlite3替代内置sqlite3(推荐)
这是无需编译的轻量方案:
- 添加
pysqlite3-binary依赖到项目中:- 若用Poetry,执行
poetry add pysqlite3-binary更新pyproject.toml - 或直接在pip安装步骤中添加:
pip install pysqlite3-binary
- 若用Poetry,执行
- 修改代码中的导入语句,替换内置模块:
import pysqlite3 as sqlite3
- 调整GitHub Actions的依赖安装步骤,确保依赖被安装:
- name: Install dependencies run: | python -m pip install --upgrade pip pip install poetry poetry install
内容的提问来源于stack exchange,提问作者Rahul A Ranger
相关产品推荐
相关产品推荐

