How to stop bazel from relying on Python2

Viewed 1394

when running bazel test Bazel seems to default to Python 2 even when --python-version flag is specified

bazel test //... --python_version PY3
INFO: From Testing //test:py-unit-tests:
==================== Test output for //test:py-unit-tests:
/usr/bin/env: 'python': No such file or directory

This is my BUILD file

py_test(
    name = "py-unit-tests",
    srcs = glob(["unit/**/*.py"]),
    deps = [
    ],
    main = "unit/unit_test_runner.py",
    timeout = "short",
)

And the test file

import sys
import unittest


class TestGeneration(unittest.TestCase):
    def test_base(self):
        pass
    def test_urdf(self):
        self.assertEqual("hello", 'test')


if __name__ == '__main__':
    unittest.main()

Bazel version: 3.3.1


Other notable things:

  1. My system has both py2 and py3 installed

  2. Py3 is located at /usr/bin/python3

  3. Py2 is located at /usr/bin/python2

There is no /usr/bin/python

1 Answers

As described in https://github.com/bazelbuild/bazel/issues/11554, the issue is that your Bazel python stub has a #!/usr/bin/env python shebang. If python is not on the PATH like in your case, the stub will fail.

Previously the only solution would be to add a symlink from python to python3, e.g. by installing

sudo apt install python-is-python3

However since https://github.com/bazelbuild/bazel/commit/763dd0ce6e1644bf895231432f616427a11d385a has landed that stub shebang has become configurable. You can now define your own py_runtime (https://docs.bazel.build/versions/main/be/python.html#py_runtime)

Alternatively, since https://github.com/bazelbuild/bazel/commit/2945ef5072f659878dfd88b421c7b80aa4fb6c80 the default shebang has also become #!/usr/bin/env python3

These two commits are only available from Bazel 5.0.0 though, so for now you might have to build Bazel yourself to get them.

Related