在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
運行
$ 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 ] | : | * | :intent([ in | inout | out | hide | in,out | inout,out | c | copy | cache | callback | inplace | aux ])dimension()common, parameterallocatableoptional, required, externaldepend([])check([])note()usercode, callstatement, callprotoargument, threadsafe, fortrannamepymethoddefentry
以上所述就是本文的全部內容了,希望大家能夠喜歡