如何从setuptools安装程序(setup.py)中生成python grpc代码? [英] How do I generate python grpc code from within a setuptools installer (setup.py)?

查看:106
本文介绍了如何从setuptools安装程序(setup.py)中生成python grpc代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在回购中有一些gRPC的原始文件,我读到提交生成的代码不好.所以我认为我需要将这一代作为软件包安装的一部分(例如setuptools,setup.py)

We have some proto files for gRPC in a repo and I read that it is not good to commit generated code. So I figured I need to have the generation as part of the package installation (e.g. setuptools, setup.py)

但是,要生成gRPC代码,您需要首先根据

However, to generate gRPC code, you need to first install the package by running pip install grpcio-tools according to the docs. But the purpose of setup.py is to automatically pull down dependencies like grpcio-tools.

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

So is there a best-practice for doing this? As in, how to generate code that depends on another python package from within setuptools? Am I better off just create a separate build.sh script that manually pip-installs and generates the code? Or should I expect users of the package to already have grpcio-tools installed?

推荐答案

据我所知,当前"最佳实践是:

As far as I know, the "current" best practice is:

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

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

Executing "pip install ." is almost equivalent to perform "pip install -r requirements.txt" + "python setup.py build" + "python setup.py install".

这是一个自定义命令,可从原始文件生成python源:

This is a custom command that generates python sources from proto files:

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命令调用,如下所示:

that is invoked customizing build_py command, like this:

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

请注意在运行方法中导入 .在安装需求之前和之后,pip似乎多次运行setup.py.因此,如果将导入放在文件之上,则构建将失败.

Note the import inside the run method. It seems that pip run setup.py several times, both before and after having installed requirements. So if you have the import on top of file, the build fails.

这篇关于如何从setuptools安装程序(setup.py)中生成python grpc代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆