如何使用Bazel的py_library导入参数

qui*_*tle 4 python build boto3 bazel

我正在尝试在Bazel构建的项目中使用Boto3,但似乎无法为该库获取正确的导入。由于Boto git存储库的缘故,所有源均位于命名文件夹botocoreboto3存储库的根目录中。导入全部为boto3.boto3,第一个对应于外部依赖项的名称,第二个为驻留的根文件夹。如何使用imports的属性py_binarypy_library规则,以进口从内boto3而不是另一种呢?

这是我的工作区外观:

//WORKSPACE

BOTOCORE_BUILD_FILE = """

py_library(
    name = "botocore",
    srcs = glob([ "botocore/**/*.py" ]),
    imports = [ "botocore" ],
    visibility = [ "//visibility:public" ],
)

"""

_BOTO3_BUILD_FILE = """

py_library(
    name = "boto3",
    srcs = glob([ "boto3/**/*.py" ]),
    imports = [ "boto3" ],
    deps = [ "@botocore//:botocore" ],
    visibility = [ "//visibility:public" ],
)

"""

new_git_repository(
    name = "botocore",
    commit = "cc3da098d06392c332a60427ff434aa51ba31699",
    remote = "https://github.com/boto/botocore.git",
    build_file_content = _BOTOCORE_BUILD_FILE,
)

new_git_repository(
    name = "boto3",
    commit = "8227503d7b1322b45052a16b197ac41fedd634e9", # 1.4.4
    remote = "https://github.com/boto/boto3.git",
    build_file_content = _BOTO3_BUILD_FILE,
)
Run Code Online (Sandbox Code Playgroud)

//BUILD

py_binary(
    name = "example",
    srcs = [ "example.py" ],
    deps = [
        "@boto3//:boto3",
    ],
)
Run Code Online (Sandbox Code Playgroud)

//example.py

import boto3

boto3.client('')
Run Code Online (Sandbox Code Playgroud)

检查构建文件夹的内容

$ ls bazel-bin/example.runfiles/*
bazel-bin/example.runfiles/__init__.py bazel-bin/example.runfiles/MANIFEST

bazel-bin/example.runfiles/boto3:
boto3  __init__.py

bazel-bin/example.runfiles/botocore:
botocore  __init__.py
Run Code Online (Sandbox Code Playgroud)

当我尝试运行示例脚本时,我AttributeError: 'module' object has no attribute 'client'可以,import boto3.boto3但是随后使用其中的任何内容都会导致缺少依赖项,例如boto3.sessions因为所有内容都嵌套在其中<target-name>.boto3

Ada*_*dam 5

我认为您的工作方向正确,但是由于python sys.path的排序,您遇到了一个细微的问题。

如果我运行您的示例并在example.py中打印出sys.path,我会看到该路径按顺序包含:

bazel-out/local-fastbuild/bin/example.runfiles
bazel-out/local-fastbuild/bin/example.runfiles/boto3/boto3
bazel-out/local-fastbuild/bin/example.runfiles/boto3
Run Code Online (Sandbox Code Playgroud)

第二行是由于imports = ['boto3']您的WORKSPACE文件中的。

我认为您希望第三行是您的import boto3出发地,因为您希望python能够看到bazel-out/local-fastbuild/bin/example.runfiles/boto3/boto3/__init__.py

因此,当python求值时import boto3,它将bazel-out/local-fastbuild/bin/example.runfiles/boto3/__init__.py 从第一个条目开始查看并使用它,而不是bazel-out/local-fastbuild/bin/example.runfiles/boto3/boto3/__init__.py从第三个条目开始。

我认为这里的答案是给您的“工作区”命名,而不是它包含的目录。例如:

# WORKSPACE
new_git_repository(
  name = "boto3_archive",
  commit = "8227503d7b1322b45052a16b197ac41fedd634e9", # 1.4.4
  remote = "https://github.com/boto/boto3.git",
  build_file_content = _BOTO3_BUILD_FILE,
)

# BUILD
py_binary(
  name = "example",
  srcs = [ "example.py" ],
  deps = [
    "@boto3_archive//:boto3",
  ],
)
Run Code Online (Sandbox Code Playgroud)

在您的示例中执行此操作时,出现以下错误:ImportError: No module named dateutil.parser,我认为这是进度。