pip下载或者安装某些包的时候,如何用命令行排除某些依赖包
为了能在pip download xxxx 的时候,过滤xxxx包的一些依赖,因为这些依赖一般自动下载最新版,但是要用的旧版本已经下载好了,不想下载新版本,
此时就要排除下载依赖,而--no-deps选项会过滤所有依赖,不是我想要的。
下面改造pip的少量代码,实现命令行排除 ,例如 pip download xxxx --exclude yyy, 例如pip download timm -d pkgs_cache --exclude torch
假如是Anaconda虚拟环境,名称叫:py3.12
那么打开以下目录,
py3.12/lib/python3.12/site-packages/pip
pip文件夹下有下面这些文件

找到:_internal/commands/download.py文件
1. 修改add_options函数,增加选项
def add_options(self): // .... self.cmd_opts.add_option( "--exclude", dest="exclude", metavar="package", default=[], action="append", help="Exclude specified package(s) from being downloaded.", ) // ....
2. 修改run函数
def run(self, options: Values, args: list[str]) -> int: // 增加一行,将要排除的包临时加到os的环境变量里 os.environ["PIP_EXCLUDE"] = ",".join(options.exclude)
找到 _internal/resolution/resolvelib/provider.py文件
3. 修改 get_dependencies函数
def get_dependencies(self, candidate: Candidate) -> Iterable[Requirement]: with_requires = not self._ignore_dependencies excludes = None try: excludes = os.environ["PIP_EXCLUDE"] except Exception: pass if excludes: exclude_list = excludes.split(",") for r in candidate.iter_dependencies(with_requires): if r is None: continue if r.project_name in exclude_list: continue yield r else: # iter_dependencies() can perform nontrivial work so delay until needed. return (r for r in candidate.iter_dependencies(with_requires) if r is not None)
通过以上设置,即可实现想要的功能,但注意这些改动只适合这一个虚拟环境。

浙公网安备 33010602011771号