【问题标题】:Embedding Fortran in Python with f2py使用 f2py 在 Python 中嵌入 Fortran
【发布时间】:2011-12-15 21:10:21
【问题描述】:

我需要一个脚本来递归遍历目录结构,从目录中的文件中提取数字,然后对这些数字执行计算。我使用 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 编译和运行 itests 和 itimes-s 后的 b.txt:

   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 会产生许多错误。 (因篇幅未发,如果有人要我可以发)

【问题讨论】:

  • 请发布示例。之后提供任何建议会容易得多。
  • 您可以将遇到相同问题的子程序减少到最低限度,然后在此处发布。
  • @steabert 和 Idigas,抱歉耽搁了,请参阅上面的示例。

标签: python fortran f2py


【解决方案1】:

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

另外,请注意,您并没有明确关闭输入和输出文件,尽管这对 f2py 的工作与否没有真正的影响。

【讨论】:

  • 因为 python 模块的名称必须与 Fortran 模块的名称不同。然后,您将拥有 pythonmodule.fortranmodule.yourfunction
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多