在Python中嵌入Fortran(使用f2py)

3 投票
1 回答
1417 浏览
提问于 2025-04-17 08:27

我需要一个脚本,能够遍历一个文件夹结构,从里面的文件中提取数字,然后对这些数字进行计算。我主要用Python来写这个脚本,但我想用Fortran来做数值计算。(因为我对Fortran更熟悉,它在数值计算方面更好用)

我正在尝试使用f2py,但总是遇到奇怪的错误。f2py对我的变量声明有意见,试图把字符类型(*)改成整数类型,并且在我变量声明后面紧跟注释时,强行在变量名后加上!。

这个子程序太长,不能在这里贴出来,但它需要两个参数,一个是输入文件名,一个是输出文件名。它会打开输入文件,读取数字,处理这些数字,然后写入输出文件。我打算用Python脚本在每个目录里写出数值文件,然后调用Fortran的子程序来处理它。

我可以尝试贴一个小一点的例子,问题是一样的,但使用f2py时有没有什么常见的“坑”?我用的是gfortran v4.6.1,python v3.2.2,还有f2py v2。

编辑: 这里有一个小例子,错误是一样的:

itimes-s.f(包含要从Python使用的子程序的文件):

  module its

  contains

  subroutine itimes(infile,outfile)

    implicit none

    ! Constants
    integer, parameter :: dp = selected_real_kind(15)

    ! Subroutine Inputs
    character(*), intent(in) :: infile    ! input file name
    character(*), intent(in) :: outfile   ! output file name

    ! Internal variables
    real(dp) :: num               ! number to read from file
    integer :: inu                ! input unit number
    integer :: outu               ! output unit number
    integer :: ios                ! IOSTAT for file read

    inu = 11
    outu = 22

    open(inu,file=infile,action='read')
    open(outu,file=outfile,action='write',access='append')

    do
      read(inu,*,IOSTAT=ios) num
      if (ios < 0) exit

      write(outu,*) num**2
    end do

  end subroutine itimes

  end module its

itests.f(Fortran驱动程序):

  program itests

  use its

  character(5) :: outfile
  character(5) :: infile

  outfile = 'b.txt'
  infile = 'a.txt'

  call itimes(infile, outfile)

  end program itests

a.txt:

1
2
3
4
5
6
7
8
9
10.2

b.txt在只用gfortran编译和运行itests和itimes-s后得到:

   1.0000000000000000     
   4.0000000000000000     
   9.0000000000000000     
   16.000000000000000     
   25.000000000000000     
   36.000000000000000     
   49.000000000000000     
   64.000000000000000     
   81.000000000000000     
   104.03999999999999     

但是,运行f2py命令f2py.py -c -m its itimes-s.f时却产生了很多错误。(因为太长没贴出来,但如果有人想要,我可以贴)

1 个回答

1

我从来没有尝试过用 f2py 来封装一个完整的 Fortran 模块。不过,如果你把模块里的 itimes 函数单独提取到一个文件里,然后再运行同样的 f2py 命令,我在本地试过的时候一切都能正常工作(使用的是 f2py v2,numpy 1.6.1,python 2.7.2,gfortran 4.1.2)。

另外,要注意的是,你并没有明确地关闭你的输入和输出文件,不过这对 f2py 的工作与否没有什么实质性的影响。

撰写回答