如何在 Cython 中正确包含头文件(setup.py)?

hyl*_*los 7 setuptools cython

我怎样才能my_math/clog.h正确地包含在包裹中my_math以让套件tox通过py.test


项目文件结构:

my_math/__init__.py
my_math/clog.h
my_math/clog.pxd
my_math/integrate.pyx
setup.py
tests/__init__.py
tests/test_log.py
tox.ini
Run Code Online (Sandbox Code Playgroud)

my_math/clog.h

my_math/__init__.py
my_math/clog.h
my_math/clog.pxd
my_math/integrate.pyx
setup.py
tests/__init__.py
tests/test_log.py
tox.ini
Run Code Online (Sandbox Code Playgroud)

my_math/integrate.pyx

#include <python.h>
#include <math.h>

#if PY_VERSION_HEX < 0x3050000 && (defined(_WIN32) || defined(_WIN64))
// Calculates log2 of number
double log2(double n);
{
    // log(n)/log(2) is log2
    double log_2 = 0.693147180559945309417232121458176568075500134360255254120680;
    return log(n) / log_2;
}
#endif
Run Code Online (Sandbox Code Playgroud)

安装程序.py

def extern from "clog.h":
    double log2(double)

def call_log2(n):
    return log2(n)
Run Code Online (Sandbox Code Playgroud)

测试/test_log.py

import os

from setuptools import setup, Extension
from setuptools.dist import Distribution
from Cython.Distutils import build_ext

Distribution(dict(setup_requires='Cython'))

ext_modules = [
    Extension("my_math.integrate", ["my_math/integrate.pyx"],
              include_dirs=['my_math'],  # path to .h file(s)
              library_dirs=['my_math'],  # path to .a or .so file(s)
              # libraries=['clog'],
              extra_compile_args = ['-I/usr/local/include',
                                    '-L/usr/local/lib'],
              depends=['my_math/clog.h']
            )
]

setup(
    name='my_math',
    package_dir={'my_math': 'my_math'},
    packages=['my_math'],
    include_package_data=True,
    package_data={'': ['*.pyx', '*.pxd', '*.h', '*.c']},
    cmdclass = {'build_ext': build_ext},
    ext_modules=ext_modules
)
Run Code Online (Sandbox Code Playgroud)

毒物文件

from pytest import approx

from my_math.integrate import call_log2

def test_call_log2():
    assert approx(call_log2(100)) == 6.64386
Run Code Online (Sandbox Code Playgroud)

my_math/__init__.py并且tests/__init__.py都是空的。


我运行python3 setup.py build_ext --inplace没有任何故障。

我可以直接调用该函数call_log2

[tox]
envlist = py36

[testenv]
deps = cython
       pytest
commands = python setup.py build_ext --inplace
           py.test tests
Run Code Online (Sandbox Code Playgroud)

但不包括tox

python3 -c 'from my_math.integrate import call_log2; print(call_log2(100))'
6.643856189774724
Run Code Online (Sandbox Code Playgroud)

如果我取消# libraries = ['clog'],注释,python3 setup.py build_ext --inplace则会产生ld: library not found for -lclog错误。

hyl*_*los 4

通过更正解决MANIFEST.in

global-include *.txt *.rst *.pyx *.pxd *.c *.h

setup.py

'': ['data/*', '*.pyx', '*.pxd', '*.c', '*.h']

MANIFEST.insetup.py必须涵盖所有文件模式以支持bdistsdist.

相关:如何使用 setuptools/distribute 包含包数据?