在python中調用fortran代碼,要用到f2py這個程序。它的項目主頁在此?,F在該項目已經合并到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
運行
$ pythonPython 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2Type "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 precisioncomplex[ | *8 | *16 | *32 ]<dim> | <start>:<end> | * | :intent([ in | inout | out | hide | in,out | inout,out | c | copy | cache | callback | inplace | aux ])dimension(<dimspec>)common, parameterallocatableoptional, required, externaldepend([<names>])check([<C-booleanexpr>])note(<LaTeX text>)usercode, callstatement, callprotoargument, threadsafe, fortrannamepymethoddefentry
以上所述就是本文的全部內容了,希望大家能夠喜歡