如何在Python setup文件中排除特定依赖包版本——解决torch v1.8.0兼容问题
Got it, let's sort out this dependency issue. The problem with your original install_requires line is that you're asking for conflicting version constraints: a package can't be both >=1.8.1 and <=1.7.1 at the same time. That's why pip is throwing that "no matching distribution" error—it's impossible to satisfy both rules.
The Correct Constraint Syntax
Instead of combining conflicting ranges, you need to specify two separate valid version ranges that pip can choose between. Use the || operator to tell pip: "install either a version ≤1.7.1, or a version ≥1.8.1". This automatically excludes 1.8.0 without any extra != clause (since 1.8.0 falls outside both ranges).
Here's how to write it in your setup.py:
install_requires=[ "torch<=1.7.1 || torch>=1.8.1", # Add your other dependencies here ]
How This Works
Let's map this to the available torch versions you listed:
- Valid versions from the older range: 0.1.2, 0.1.2.post1, ..., 1.7.1
- Valid versions from the newer range: 1.8.1, and any future versions above it
- Automatically excluded: 1.8.0 (it doesn't fit either range)
This keeps compatibility with your desired older versions while skipping the broken 1.8.0 release, and avoids forcing users to download a newer torch if they don't need it.
If Using pyproject.toml
If you're using a modern pyproject.toml file for dependencies, the syntax is identical:
[project] dependencies = [ "torch<=1.7.1 || torch>=1.8.1", # Other dependencies go here ]
内容的提问来源于stack exchange,提问作者kiranr

