如何在Poetry构建流水线中排除Tensorflow依赖?
Got it, let's fix that slow GitHub Actions build by skipping TensorFlow during your automated tests. Here are two reliable approaches using Poetry's built-in features, depending on your setup:
Approach 1: Use Poetry Dependency Groups (Recommended for Poetry 1.2+)
Poetry 1.2+ introduced dependency groups, which let you organize dependencies by purpose (like production-only, ML-specific, etc.). This is the cleanest way to separate TensorFlow from your test dependencies.
Step 1: Update pyproject.toml
Move TensorFlow out of your default dependencies into a dedicated group (e.g., tf or production):
# Remove tensorflow from [tool.poetry.dependencies], then add: [tool.poetry.group.tf.dependencies] tensorflow = "^2.15" # Replace with your actual version
Step 2: Local/Production Installation
When you need TensorFlow locally or for production builds, install with the group included:
poetry install --with tf
Step 3: Update GitHub Actions Workflow
In your workflow YAML, install dependencies without the tf group to skip TensorFlow:
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.10" # Match your project's Python version - name: Install Poetry run: | curl -sSL https://install.python-poetry.org | python3 - echo "$HOME/.local/bin" >> $GITHUB_PATH - name: Install dependencies (skip TensorFlow) run: poetry install --without tf - name: Run tests run: poetry run pytest
Approach 2: Use Optional Dependencies (Compatible with Older Poetry Versions)
If you're stuck on Poetry 1.1 or earlier, optional dependencies work great for excluding single large packages like TensorFlow.
Step 1: Update pyproject.toml
Mark TensorFlow as optional and define an "extra" set for it:
[tool.poetry.dependencies] python = "^3.10" tensorflow = { version = "^2.15", optional = true } [tool.poetry.extras] tf = ["tensorflow"]
Step 2: Local/Production Installation
Install with the extra flag when you need TensorFlow:
poetry install --extras tf # Shorthand: poetry install -E tf
Step 3: Update GitHub Actions Workflow
Optional dependencies aren't installed by default, so just use the standard install command:
# ... (same checkout/setup steps as above) - name: Install dependencies (skip TensorFlow) run: poetry install - name: Run tests run: poetry run pytest
Critical Notes
- Test Code Compatibility: Make sure your test suite doesn't hard-import TensorFlow. If you have code that uses TensorFlow conditionally, wrap imports in a try-except block:
try: import tensorflow as tf except ImportError: tf = None # Or skip related test cases with pytest.mark.skip - Verify Locally: Test the install command (e.g.,
poetry install --without tf) on your machine first to confirm TensorFlow isn't installed and your tests still pass.
内容的提问来源于stack exchange,提问作者Daan Klijn

