Search code examples
python-3.xbazel

make Bazel use python 3


I would like to run my py_test with python 3 in Bazel.

py_library(
    name = "foo",
    srcs = ["foo.py"]
)

py_test(
    name = "foo_test",
    srcs = glob(["foo_test.py",]),
    deps = [":foo"]
)

py_runtime(
    name = "python-3.6.3",
    files = [],
    interpreter_path = "/usr/local/bin/python3",
)

I was able to achieve this using command

bazel test --python_top=//path/to/foo:python-3.6.3 foo_test

However, I would like to import python3 to bazel sandbox with new_http_archive and provide the interpreter_path for the py_runtime rule that points to that http_archive within bazel sandbox. So far I am not able to find what is the interpreter_path... Do I have to reference the http_archive label somewhere from the py_runtime or somewhere else?

new_http_archive(
name = "python_version",
urls = ["https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz"],
strip_prefix = "Python-3.6.3",
build_file_content = """
py_library(
    name = "python_srcs",
    srcs = glob(["Lib/*.py"]),
    visibility = ["//visibility:public"]
)"""
)

Solution

  • The tgz that you're downloading doesn't contain an interpreter. It contains the source code for the interpreter. If you want to build the interpreter as part of your build, you could do something like this

    new_http_archive(
        name = "python_version",
        urls = ["https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz"],
        strip_prefix = "Python-3.6.3",
        build_file_content = """
    genrule(
        name = "build_python",
        srcs = glob(["**"]),
        outs = ["python"],
        cmd = "./external/python_version/configure && make && cp python $@",
        visibility = ["//visibility:public"],
    )""",
    )
    

    And then your py_runtime rule would set the interpreter attribute (not interpreter_path):

    py_runtime(
        name = "python-3.6.3",
        files = [],
        interpreter = "@python_version//:python",
    )