如何通过pip从私有GitHub仓库安装指定版本范围的软件包?
Great question! Working with private Git repositories and version ranges in pip can feel a bit opaque at first, but there are clear ways to handle both tag-based ranges and branch-based installs with version constraints.
Tag-Based Version Ranges (0.1.9 to 1.0.0)
You’re already on the right track with tag-specific installs. To define a range of versions (inclusive of 0.1.9, exclusive of 1.0.0), you just need to format the version constraints correctly after the @ symbol in your requirements.txt entry. The correct syntax is:
git+ssh://git@github.com/myuser/mypackage.git@>=0.1.9,<1.0.0#egg=mypackage
This tells pip to look for all Git tags in your private repo that match the semantic version range >=0.1.9,<1.0.0 and install the latest valid version. Just make sure your tags follow proper semantic versioning (SemVer) format like 0.1.9, 0.2.0, etc.—pip relies on this to parse the range correctly.
Using Master Branch with Version Ranges
If you want to install from the master branch but enforce version constraints, there’s a catch: master is a dynamic branch, so pip can’t directly check branch commits against version ranges unless your package explicitly defines its version in setup.py or pyproject.toml.
Here’s how to set it up:
- Ensure your package’s build configuration (either
setup.pyorpyproject.toml) includes a valid version number that updates as you push tomaster. - In your requirements.txt, use this syntax to pin to
masterand add the version constraint:
git+ssh://git@github.com/myuser/mypackage.git@master#egg=mypackage,>=0.1.9,<1.0.0
However, keep in mind this approach has risks: if a commit to master updates the code but doesn’t bump the version (or bumps it outside your range), pip might either install an outdated version or throw an error. For stability, tag-based ranges are almost always preferable over branch-based ones with version constraints.
Quick Notes
- Double-check your SSH access to the private repo:
pipwill fail to clone if your local SSH key isn’t authorized for the repo. - If you’re using
pyproject.tomlinstead ofrequirements.txt, the syntax is similar but structured differently:mypackage = {url = "git+ssh://git@github.com/myuser/mypackage.git", version = ">=0.1.9,<1.0.0"}
内容的提问来源于stack exchange,提问作者Rene B.

