问题
I need a script to recurse across a directory structure, extract numbers from files in the directories, then perform calculations on those numbers. I am using Python as the main language for the script, but wanted to use Fortran for the numerical computations. (I am more comfortable with Fortran and it is a better tool for numerical work)
I am trying to use f2py, but I keep getting strange errors. f2py is complaining about my variable declarations, trying to change character(*) to integer and appending ! onto my variable names when I have a comment immediately following the variable declaration.
The subroutine is too long to post here, but takes two arguments, an input file name and output file name. It opens the input file, reads the numbers, processes them, then writes to the output file. I intend to use the Python script to write the numerical file in each directory and call the Fortran subroutine on it.
I can try to post a smaller example with the same issues, but are there any common 'gotchas' with f2py? I am using gfortran v4.6.1, python v3.2.2, and f2py v2.
EDIT: Here is a small example with the same errors:
itimes-s.f (File containing subroutine to be used from 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 driver program):
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 after compiling and running itests and itimes-s using gfortran only:
1.0000000000000000
4.0000000000000000
9.0000000000000000
16.000000000000000
25.000000000000000
36.000000000000000
49.000000000000000
64.000000000000000
81.000000000000000
104.03999999999999
Running f2py using f2py.py -c -m its itimes-s.f
produces numerous errors however. (not posted due to length, but if someone wants I can post them)
回答1:
I have never tried using f2py to wrap a full Fortran module. However, if you extract the itimes
function from the module into its own file and then run the same f2py
command, everything appears to work when I tried it locally (f2py v2, numpy 1.6.1, python 2.7.2, gfortran 4.1.2).
Also, note that you are not explicitly closing your input and output files, though this has no real bearing on f2py's working or not.
来源:https://stackoverflow.com/questions/8526632/embedding-fortran-in-python-with-f2py