能否通过setup.py配置extras_require实现pipenv多环境部署?
Absolutely, your plan to switch from pip-tools to Pipenv using extras_require in setup.py is a solid way to maintain multi-environment dependency management. Let’s break down how to make this work smoothly:
1. Complete setup.py Configuration
First, you’ll need to implement the load_requirements function you referenced—since it’s not a built-in utility, here’s a reliable implementation to read your dependency files correctly:
from setuptools import setup def load_requirements(filename): """Load requirements from a text file, skipping comments and empty lines.""" with open(filename, 'r') as f: return [ line.strip() for line in f if line.strip() and not line.startswith('#') ] setup( # ... keep your existing setup config (name, version, author, etc.) ... install_requires=load_requirements('requirements.txt'), extras_require={ 'dev': load_requirements('dev-requirements.txt'), 'web': load_requirements('web-requirements.txt'), } )
This setup ensures your core dependencies (from requirements.txt) are installed by default, while dev and web act as optional, environment-specific add-ons.
2. Verify Your Pipenv Commands
Your proposed deployment commands are correct—let’s break down what each part does to eliminate confusion:
- For Web environment:
pipenv install --dev --ignore-pipfile '-e .[web]'--dev: Installs dev-focused dependencies (safe to keep here even with extras, though--ignore-pipfilemeans it won’t reference a Pipfile’s dev section)--ignore-pipfile: Tells Pipenv to bypass any existingPipfile/Pipfile.lockand use yoursetup.pyconfiguration directly-e .[web]: Installs your package in editable mode (so code changes take effect immediately) and pulls in thewebextra dependencies
- For development:
pipenv install --dev --ignore-pipfile '-e .[dev]'works the same way, just targeting thedevextras instead.
3. Key Notes to Avoid Headaches
- Double-check your
*-requirements.txtfiles: each dependency should be on its own line, and comments (starting with#) are fine—ourload_requirementsfunction skips them automatically - If you don’t have a core
requirements.txt, setinstall_requiresto an empty list, but keeping a base set of dependencies is best practice for core app functionality - Use a recent Pipenv version (v2023.9 or newer) to avoid bugs with editable installs and extras handling
Optional: Alternate Pipenv-First Approach
If you want to fully lean into Pipenv’s ecosystem, you could define these extras directly in a Pipfile instead of setup.py, but your current method is totally valid if you prefer keeping dependency lists in separate .txt files for consistency with your old workflow.
内容的提问来源于stack exchange,提问作者Forest Monsen

