【问题标题】:How do I generate python grpc code from within a setuptools installer (setup.py)?如何从 setuptools 安装程序 (setup.py) 中生成 python grpc 代码?
【发布时间】:2019-03-30 09:29:39
【问题描述】:

我们在 repo 中有一些 gRPC 的 proto 文件,我读到提交生成的代码并不好。所以我想我需要将生成作为包安装的一部分(例如 setuptools、setup.py)

但是,要生成gRPC代码,需要先按照the docs运行pip install grpcio-tools安装包。但是 setup.py 的目的是自动拉下 grpcio-tools 之类的依赖项。

那么,是否有这样做的最佳实践?如,如何从 setuptools 中生成依赖于另一个 python 包的代码?我最好只创建一个单独的build.sh 脚本来手动安装并生成代码吗?或者我应该期望该软件包的用户已经安装了 grpcio-tools

【问题讨论】:

  • 好问题。您可以在构建包时生成这些文件;您需要的任何包都可以通过setup_requires 参数传递。

标签: python setuptools grpc grpc-python


【解决方案1】:

据我所知,“当前”的最佳做法是:

  • pip 管理依赖项
  • setup.py 执行构建

执行“pip install”。几乎等同于执行“pip install -r requirements.txt”+“python setup.py build”+“python setup.py install”。

这是一个从 proto 文件生成 python 源的自定义命令:

class GrpcTool (Command):
    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        import grpc_tools.protoc

        proto_include = pkg_resources.resource_filename('grpc_tools', '_proto')

        grpc_tools.protoc.main([
            'grpc_tools.protoc',
            '-I{}'.format(proto_include),
            '--python_out=SOME_PATH/',
            '--grpc_python_out=SOME_PATH/',
            'SOME_PROTO.proto'
        ])

即调用自定义 build_py 命令,如下所示:

class BuildPyCommand (build_py):
    def run(self):
        self.run_command('grpc')
        super(BuildPyCommand, self).run()

注意 inside run 方法的导入。似乎 pip 在安装要求之前和之后运行了 setup.py 几次。因此,如果您在文件顶部进行导入,则构建会失败。

【讨论】:

    【解决方案2】:

    除了@makeroo 方法,另一种方法是将grpc_tools 模块作为子进程执行。

    这种方法的好处是肯定会收到生成结果; 0 表示成功,1 表示错误。

    proto_files = ["proto/file1.proto", "proto/file2.proto"]
    
    import subprocess
    for file in proto_files:
        args = "--proto_path=. --python_out=. --grpc_python_out=. {0}".format(file)
        result = subprocess.call("python -m grpc_tools.protoc " + args, shell=True)
        print("grpc generation result for '{0}': code {1}".format(file, result))
    

    以上代码将创建生成的python文件到proto文件所在的.proto目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多