使用f2py将Fortran嵌入Python

3
我需要一个脚本来递归遍历一个目录结构,在目录中的文件中提取数字,然后对这些数字进行计算。我使用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

使用gfortran编译和运行b.txt文件后的itest和itimes-s结果如下:

   1.0000000000000000     
   4.0000000000000000     
   9.0000000000000000     
   16.000000000000000     
   25.000000000000000     
   36.000000000000000     
   49.000000000000000     
   64.000000000000000     
   81.000000000000000     
   104.03999999999999     

使用f2py.py -c -m its itimes-s.f运行f2py会产生大量错误。 (由于长度未发布,但如果有人想要,我可以发布它们)

3
请发布示例。在此基础上给出任何建议都会更容易些。 - Rook
1
你可以将子程序简化到最小,使其仍然存在相同的问题,然后在这里发布。 - steabert
@steabert和Idigas,抱歉耽搁了, 请参考上面的例子。 - astay13
1个回答

1

我从未尝试使用f2py来包装整个Fortran模块。但是,如果您将itimes函数从模块中提取到自己的文件中,然后运行相同的f2py命令,在我本地尝试时一切似乎都可以工作(f2py v2,numpy 1.6.1,python 2.7.2,gfortran 4.1.2)。

此外,请注意,您没有明确关闭输入和输出文件,尽管这与f2py的工作与否无关。


1
因为Python模块的名称必须与Fortran模块的名称不同。因此,您将拥有pythonmodule.fortranmodule.yourfunction。 - Vladimir F Героям слава

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接