如何将Cython与诗歌结合使用?

问题描述

我的项目中有一个文件,出于性能考虑,我希望对其进行编译:

mylibrary / myfile.py

如何通过诗歌实现这一目标?

解决方法

诗歌中有未记录的功能。将此添加到您的pyproject.toml

[tool.poetry]
...
build = 'build.py'

[build-system]
requires = ["poetry>=0.12","cython"]
build-backend = "poetry.masonry.api"

这是在隐式生成的setup.py中运行build.py:build()函数。 这是我们建造的地方。

因此,创建一个提供build.py功能的build()

import os

# See if Cython is installed
try:
    from Cython.Build import cythonize
# Do nothing if Cython is not available
except ImportError:
    # Got to provide this function. Otherwise,poetry will fail
    def build(setup_kwargs):
        pass
# Cython is installed. Compile
else:
    from setuptools import Extension
    from setuptools.dist import Distribution
    from distutils.command.build_ext import build_ext

    # This function will be executed in setup.py:
    def build(setup_kwargs):
        # The file you want to compile
        extensions = [
            "mylibrary/myfile.py"
        ]

        # gcc arguments hack: enable optimizations
        os.environ['CFLAGS'] = '-O3'

        # Build
        setup_kwargs.update({
            'ext_modules': cythonize(
                extensions,language_level=3,compiler_directives={'linetrace': True},),'cmdclass': {'build_ext': build_ext}
        })

现在,当您执行poetry build时,什么都不会发生。 但是,如果将此软件包安装在其他位置,则会对其进行编译。

您还可以使用以下方法手动构建它:

$ cythonize -X language_level=3 -a -i mylibrary/myfile.py

最后,似乎您无法将二进制包发布到PyPi。 解决方案是将构建限制为“ sdist”:

$ poetry build -f sdist
$ poetry publish

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...