如何在构建过程中生成 python 代码并将它们包含在 python 轮中?

问题描述

我们有一个通过

生成代码的包
$PYTHON -m grpc_tools.protoc -I="foo_proto" --python-out="$package/out" \
         --grpc_python_out="$package/out" ./path/to/file.proto

通过以下方式将其集成(读入)到我们的 setup.py 建筑物中:

from distutils.command.build_py import build_py

class Buildpycommand(build_py):
    """
    Generate GRPC code before building the package.
    """
    def run(self):
        import subprocess
        subprocess.call(["./bin/generate_grpc.sh",sys.executable],shell=True)
        build_py.run(self)

setup(
      ....
      cmdclass={
        'build_py': Buildpycommand
    },)

虽然丑陋,但在使用旧版 setup.py 构建时似乎可以工作,但是当使用 wheel 构建包时,它根本不起作用。

在通过 wheel 安装我的软件包时如何使这项工作正常进行?

解决方法

您也可以覆盖车轮构建过程:

from wheel.bdist_wheel import bdist_wheel
from distutils.command.build_py import build_py
import subprocess


def generate_grpc():
    subprocess.call(["./bin/generate_grpc.sh",sys.executable],shell=True)


class BuildPyCommand(build_py):
    """
    Generate GRPC code before building the package.
    """
    def run(self):
        generate_grpc()
        build_py.run(self)


class BDistWheelCommand(bdist_wheel):
    """
    Generate GRPC code before building a wheel.
    """
    def run(self):
        generate_grpc()
        bdist_wheel.run(self)


setup(
      ....
      cmdclass={
        'build_py': BuildPyCommand,'bdist_wheel': BDistWheelCommand
    },)