使用Bazel运行Python二进制文件时遇仓库解析错误求助
问题
执行bazel run projects/my-python-app/...运行Python二进制文件时出现错误:
ERROR: /private/var/tmp/_bazel_justin/84cef48b5ae183d272bc73733d19e8e1/external/python_deps_pypi__flask/BUILD.bazel:11:11: no such package '@python_deps_pypi__itsdangerous//': The repository '@python_deps_pypi__itsdangerous' could not be resolved: Repository '@python_deps_pypi__itsdangerous' is not defined and referenced by '@python_deps_pypi__flask//:pkg' ERROR: Analysis of target '//projects/my-python-app:main' failed; build aborted:
相关配置文件如下:
WORKSPACE 文件
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") rules_python_version = "740825b7f74930c62f44af95c9a4c1bd428d2c53" # Latest @ 2021-06-23 http_archive( name = "rules_python", # Bazel will print the proper value to add here during the first build. # sha256 = "FIXME", strip_prefix = "rules_python-{}".format(rules_python_version), url = "https://github.com/bazelbuild/rules_python/archive/{}.zip".format(rules_python_version), ) load("@rules_python//python:pip.bzl", "pip_parse") # Create a central repo that knows about the dependencies needed from # requirements_lock.txt. pip_parse( name = "python_deps", requirements_lock = "//third_party:requirements_lock.txt", ) # Load the starlark macro which will define your dependencies. load("@python_deps//:requirements.bzl", "install_deps") # Call it to define repos for your requirements. install_deps()
requirements_lock.txt 文件
Flask==2.0.2
BUILD 文件
load("@python_deps//:requirements.bzl", "requirement") py_binary( name = "main", srcs = ["main.py"], deps = [ "//projects/calculator:calculator", requirement("Flask"), ], )
用户按rules_python的README操作,询问错误原因。
原因与解决方法
这个错误的核心是**requirements_lock.txt仅声明了Flask直接依赖,未包含其所有间接依赖(比如itsdangerous)**。pip_parse需要完整的锁定文件,涵盖所有直接和间接依赖包,否则Bazel无法解析这些缺失依赖对应的仓库。
解决步骤:
生成完整的锁定文件:在本地Python环境中执行命令,生成包含所有依赖的
requirements_lock.txt# 方法1:用pip freeze生成 pip freeze --all > third_party/requirements_lock.txt # 方法2:用pip-tools生成(推荐,可生成带哈希的锁定文件) pip-compile --generate-hashes requirements.in生成后的文件应包含Flask及其所有依赖(如itsdangerous、Werkzeug、Jinja2等)。
清理缓存并重新构建:执行以下命令清除Bazel旧缓存,避免残留配置干扰
bazel clean --expunge bazel run projects/my-python-app/...
补充说明:pip_parse会根据锁定文件中的每个包创建对应的Bazel仓库。如果仅指定Flask,Bazel处理Flask的BUILD配置时,找不到其依赖包的仓库定义,就会抛出上述错误。
内容的提问来源于stack exchange,提问作者jlcv
相关产品推荐
相关产品推荐

