用f2py在Python中嵌入Fortran

2024-05-19 05:53:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个脚本在目录结构中递归,从目录中的文件中提取数字,然后对这些数字执行计算。我使用Python作为脚本的主要语言,但希望使用Fortran进行数值计算。(我对Fortran比较熟悉,它是一个更好的数值计算工具)

我试着用f2py,但是我总是遇到奇怪的错误。f2py正在抱怨我的变量声明,试图将字符(*)改为整数并追加!当我在变量声明后面有一个注释的时候。在

子例程太长,无法在此处发布,但接受两个参数:输入文件名和输出文件名。它打开输入文件,读取数字,处理它们,然后写入输出文件。我打算使用Python脚本在每个目录中编写数值文件,并在其中调用Fortran子例程。在

我可以试着用同样的问题发布一个较小的例子,但是f2py有什么共同点吗?我使用的是gfortran v4.6.1、pythonv3.2.2和f2pyv2。在

编辑:下面是一个小例子,有相同的错误:

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驱动程序程序):

^{pr2}$

文本:

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


Tags: 文件目录脚本read错误数字integer例程
1条回答
网友
1楼 · 发布于 2024-05-19 05:53:28

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

另外,请注意,您并没有显式地关闭输入和输出文件,尽管这对f2py的工作与否没有实际意义。在

相关问题 更多 >

    热门问题