我希望使用 setuptools 将包部署到 PyPi。但是,包的核心部分实际上是用Fortran编写的,我使用f2py将其包装在python中。基本上项目的结构如下所示:
我的项目
模块 myfunc.py 导入 hello.so (
import my_project.hello
),然后可以被 myfunc.py 中的函数使用。这在我的机器上完美运行。然后我尝试了标准 setuptools 安装:
sudo python3 setup.py install
在我的 Ubuntu 上,它安装得很好。但不幸的是,在导入时,它抛出 ModuleNotFoundError: No module named 'hello'
.现在,据我所知,在基于 Linux 的系统上,对于 python,共享库 *.so 存储在
/usr/lib/python3/dist-packages/
中。 .所以我手动复制了这个hello.so
在那里,我得到了一个工作包!但当然这仅适用于本地。我想做的是告诉 setuptools 包含 hello.so
在 python-egg 内部并自动进行复制等操作,以便当用户使用时 pip3 install my_package
,他们将自动访问此共享库。我可以看到 numpy 以某种方式实现了这一点,但即使查看了他们的代码,我也无法解码他们是如何做到的。有人可以帮我弄这个吗?提前致谢。
最佳答案
这是基于 F2PY's documentation 的方法(该示例涵盖构建多个 F2PY 模块,以及每个模块的多个源文件),利用 numpy.distutils
,支持 Fortran 源文件。
具有多个 F2PY 扩展模块的最小示例的结构基于 src
directory layout .它不是必需/必需的,但具有以下优点:除非已成功安装包,否则测试例程无法运行。
源布局
my_project
|
+-- src
| |
| +-- my_project
| |
| +-- __init__.py
| +-- mod1.py
| +-- funcs_m.f90
| +-- two
| |
| +-- pluss2.f90
| +-- times2.f90
|
+-- test_my_project.py
+-- setup.py
from setuptools import find_packages
from numpy.distutils.core import setup, Extension
ext1 = Extension(name='my_project.modf90',
sources=['src/my_project/funcs_m.f90'],
f2py_options=['--quiet'],
)
ext2 = Extension(name='my_project.oldf90',
sources=['src/my_project/two/plus2.f90', 'src/my_project/two/times2.f90'],
f2py_options=['--quiet'],
)
setup(name="my_project",
version="0.0.1",
package_dir={"": "src"},
packages=find_packages(where="src"),
ext_modules=[ext1, ext2])
__init__.py
文件为空。 (如果需要,可以例如在此处导入 F2PY 模块)def add(a, b):
""" add inputs a and b, and return """
return a + b
module funcs_m
implicit none
contains
subroutine add(a, b, c)
integer, intent(in) :: a
integer, intent(in) :: b
integer, intent(out) :: c
c = a + b
end subroutine add
end module funcs_m
subroutine plus2(x, y)
integer, intent(in) :: x
integer, intent(out) :: y
y = x + 2
end subroutine plus2
subroutine times2(x, y)
integer, intent(in) :: x
integer, intent(out) :: y
y = x * 2
end subroutine times2
import my_project.mod1
import my_project.oldf90
import my_project.modf90
print("mod1.add: 1 + 2 = ", my_project.mod1.add(1, 2))
print("modf90.funcs_m.add: 1 + 2 = ", my_project.modf90.funcs_m.add(1, 2))
x = 1
x = my_project.oldf90.plus2(x)
print("oldf90.plus2: 1 + 2 = ", x)
x = my_project.oldf90.times2(x)
print("oldf90.plus2: 3 * 2 = ", x)
安装现在,可以使用
pip
安装软件包。有几个advantages使用 pip
(包括易于升级或卸载)而不是 setup.py install
(但这仍然可以用于构建分发包!)。来自包含 setup.py
的目录:> python -m pip install .
测试然后,测试刚刚安装的包
> python test_my_project.py
mod1.add: 1 + 2 = 3
modf90.funcs_m.add: 1 + 2 = 3
oldf90.plus2: 1 + 2 = 3
oldf90.plus2: 3 * 2 = 6
此设置已在 Windows 10(带 ifort)、Ubuntu 18.04(带 gfortran)和 MacOS High Sierra(带 gfortran)上成功测试,全部使用 Python 3.6.3。
关于python-3.x - 使用 setuptools 在 python 包中链接 f2py 生成的 *.so 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64950460/