2011-12-15 94 views
2

我需要一个脚本来递归跨目录结构,从目录中的文件中提取数字,然后对这些数字执行计算。我使用Python作为脚本的主要语言,但想要使用Fortran进行数值计算。 (我更喜欢Fortran,它是一个更好的数值工具)使用f2py嵌入Python中的Fortran

我正在尝试使用f2py,但我不断收到奇怪的错误。 f2py正在抱怨我的变量声明,试图将字符(*)更改为整数并追加!当我在变量声明之后立即注释时,将其添加到我的变量名称中。

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

我可以尝试发布一个相同问题的小例子,但是有没有与f2py共同'陷阱'?我使用的是gfortran v4.6.1,python v3.2.2和f2py v2。

编辑:这里是一个小例子具有相同的错误:

itimes-SF(含有子程序从蟒使用的文件):

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:

编译和运行itests后

b.txt itimes-S仅使用gfortran:但是

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 2011-12-15 23:12:19

+1

您可以将您的子程序减少到具有相同问题的最小程度,然后将其发布到此处。 – steabert 2011-12-16 13:28:50

回答

1

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

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