python调用fortran模块

yipeiwu_com5年前Python基础

在python中调用fortran代码,要用到f2py这个程序。它的项目主页在此。现在该项目已经合并到numpy中了,先安装python再装好numpy,就可以使用f2py。不过对windows平台必须使用gnu的fortran编译器gfortran,在此下载。装完了python,numpy和gfortran这三样东西之后,还必须更改如下几个环境变量:

    1.在$PATH中添加gfortran的路径,我的是c:\Program Files\pythonxy\mingw\bin\

    2.在$PATH中添加python的路径,我的是c:\Python26\

    3.新建环境变量C_INCLUDE_PATH,添加gfortran头文件的路径,我的是c:\Program Files\pythonxy\mingw\include\

好啦现在f2py就可以用了。新建fortran程序foo.f90如下

foo.f90

subroutine hello (a)
 
integer a
 
  write(*,*)'Hello from Fortran90!!!',a
 
end subroutine hello

编译

f2py -m foo -c foo.f90 

运行

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.hello(15)
 Hello from Fortran90!!!     15

另外附上f2py支持的数据类型有

integer[ | *1 | *2 | *4 | *8 ], logical[ | *1 | *2 | *4 | *8 ]
integer*([ -1 | -2 | -4 | -8 ])
character[ | *(*) | *1 | *2 | *3 | ... ]
real[ | *4 | *8 | *16 ], double precision
complex[ | *8 | *16 | *32 ]
<dim> | <start>:<end> | * | :
intent([ in | inout | out | hide | in,out | inout,out | c |
     copy | cache | callback | inplace | aux ])
dimension(<dimspec>)
common, parameter
allocatable
optional, required, external
depend([<names>])
check([<C-booleanexpr>])
note(<LaTeX text>)
usercode, callstatement, callprotoargument, threadsafe, fortranname
pymethoddef
entry

以上所述就是本文的全部内容了,希望大家能够喜欢

相关文章

用 Python 爬了爬自己的微信朋友(实例讲解)

用 Python 爬了爬自己的微信朋友(实例讲解)

最近几天干啥都不来劲,昨晚偶然了解到 Python 里的 itchat 包,它已经完成了 wechat 的个人账号 API 接口,使爬取个人微信信息更加方便。鉴于自己很早之前就想知道诸如...

python中使用 xlwt 操作excel的常见方法与问题

前言 Python可以操作Excel的模块不止一种,我习惯使用的写入模块是xlwt(一般都是读写模块分开的) python中使用xlwt操作excel非常方,和Java使用调框架apac...

使用Python OpenCV为CNN增加图像样本的实现

使用Python OpenCV为CNN增加图像样本的实现

我们在做深度学习的过程中,经常面临图片样本不足、不平衡的情况,在本文中,作者结合实际工作经验,通过图像的移动、缩放、旋转、增加噪声等图像变换技术,能快速、简便的增加样本数量。 本文所有案...

Python在Windows和在Linux下调用动态链接库的教程

Python在Windows和在Linux下调用动态链接库的教程

Linux系统下调用动态库(.so) 1、linuxany.c代码如下: #include "stdio.h" void display(char* msg){ p...

简单了解python反射机制的一些知识

反射 反射机制就是在运行时,动态的确定对象的类型,并可以通过字符串调用对象属性、方法、导入模块,是一种基于字符串的事件驱动。 解释型语言:程序不需要编译,程序在运行时才翻译成机器语言,每...