中setup()之前的Pip install包设置.py

2024-04-29 14:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些.protogRPC文件,我想编译为设置.py脚本。这需要运行from grpc_tools import protoc并在setup(args)之前调用protoc。目标是编译并安装来自pip install pkgname的pb文件。在

例如

# setup.py

# generate our pb2 files in the temp directory structure
compile_protobufs(pkgname)

# this will package the generated files and put them in site-packages or .whl
setup(
    name=pkgname,
    install_requires=['grpcio-tools', ...],
    ...
)

这正如预期的那样工作,我可以在我的站点包或轮子中获得pb文件,而不必将它们存在于源文件夹中。但是,这个模式意味着我不能天真地从头开始pip install pkgname,因为步骤compile_protobufs依赖于grpcio-tools,直到setup()才安装。在

我可以使用setup\u requires,但是that is on the chopping block。我可以先安装依赖项(现在我使用RUN pip install -r build-require.txt && pip install pkgname/),但似乎仍然应该有一种更干净的方法。在

我是否正确地使用了这种模式,或者我遗漏了一些包装习惯用法?在

我的标准:

  • 通常这是在一个容器中运行的,所以尽量减少外部dep
  • 我希望每次我pip install时重新生成_pb2.py文件
  • 这些文件还需要进入任何.whl或tar。在

Tags: installpip文件theinpysetupfiles
1条回答
网友
1楼 · 发布于 2024-04-29 14:25:04

看起来这里已经有记载了:

https://github.com/grpc/grpc/tree/master/tools/distrib/python/grpcio_tools#usage

所以你的setup.py可以是这样的:

#!/usr/bin/env python3

import distutils.command.install
import setuptools

class build_package_protos(setuptools.Command):
    user_options = []
    def initialize_options(self):
        pass
    def finalize_options(self):
        pass
    def run(self):
        from grpc_tools import command
        command.build_package_protos(self.distribution.package_dir[''])

class install(distutils.command.install.install):
    _sub_command = ('build_package_protos', None,)
    _sub_commands = distutils.command.install.install.sub_commands
    sub_commands = [_sub_command] + _sub_commands

def setup():
    setuptools.setup(
        # see 'setup.cfg'
        cmdclass={
            'build_package_protos': build_package_protos,
            'install': install,
        },
        setup_requires=[
            'grpcio-tools',
        ],
    )

if __name__ == '__main__':
    setup()

相关问题 更多 >