f2py - Fortran to Python interface generator
f2py实际上是Fortran到Python接口生成器 (interface generator)。
f2py模块安装
首先要确保Python已经包含numpy模块,因为numpy模块自带f2py模块,如果没有需要提前安装numpy。
numpy安装
// numpy安装
pip install numpy
f2py安装的路径
安装好numpy之后,f2py模块就有了,此时需要找到f2py的安装路径,才能够使用f2py命令,我看很多笔记只给出了一条命令
f2py -m test -c test.f90
实际上,这样是会出问题的。以防万一,最好先找到f2py的安装目录,可以使用如下命令查找,
// 查找f2py的安装路径
whereis f2py
// 比如我的路径是在bin目录下
/usr/bin/f2py
f2py模块调用Fortran程序
作为测试,可以写一个简单的Fortran程序test.f90,
// 测试程序test.f90
subroutine hello_world (number)
integer number
write(*,*)'Hello world !',number
end subroutine hello_world
上述程序参考https://blog.csdn.net/weixin_33909059/article/details/92177487
f2py生成test.f90的Python模块
// f2py调用test.f90
python /usr/bin/f2py -m test -c test.f90
// /usr/bin/f2py为f2py的路径
// -m 后跟的是新生成的python模块
// -c 后面跟的是fortran程序
其实还有其他的指令,找到一个链接,非常详细地介绍了不同指令,
http://manpages.ubuntu.com/manpages/trusty/man1/f2py.1.html.
Python调用Fortran程序
可以用文本编辑器写一个简单的f2py_test.py程序,
import test //import生成的Python模块 test+
test.hello_world(13) //用 test模块调用Fortran的hello_world函数
这时,就会出现Fortran程序的运行结果了,over!!!!
f2py转换多个Fortran程序的shell脚本
实际上,通常我们需要转换多个Fortran程序,此时一个一个在终端输入,效率未免太低了,就可以将多个命令写成shell脚本文件,直接执行脚本文件即可,
// 多个Fortran程序,f2py转换的shell脚本 test.sh
#!/bin/sh
python /usr/bin/f2py -m test -c test.f90
python /usr/bin/f2py -m fun1 -c function1.f90
python /usr/bin/f2py -m fun2 -c function2.f90
python /usr/bin/f2py -m fun3 -c function3.f90
// .....
将其保存成 ‘test.sh’文件,然后执行如下命令,
// 多个Fortran程序,f2py转换的shell脚本 test.sh
chmod a+x test.sh
// .....
使脚本具备执行权利,否则会报错:permission denied
终端执行脚本test.sh
然后,在终端中,执行脚本文件test.sh,实现批量处理多个Fortran函数,
// 执行shell脚本,实现批量处理
./test.sh
// .....
版权声明:本文为a1367790917原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。