首页 > 解决方案 > f2py:如何从 python 中的 fortran 库中打开和读取字节交换(大端)文件?

问题描述

我有一个以大端格式写入的文件。我写了一个库来访问这个文件。现在我尝试使用这个库在 python 脚本中访问这个文件。为此,我编写了一些例程并使用 f2py 进行编译。问题是在 gfortran(我使用的一个编译器)中,选项“-fconvert=big-endian”只有在主程序中使用时才有效,而不是在库中。所以我无法在 python 中正确访问这个文件。

下面我举一个小例子来重现这个问题:

文件“fileTest.bin”是由这个程序创建的:

program ttt
   implicit none
   real(kind=4) :: m(2,2)

   m=10.0

   open(unit=100,file='fileTeste.bin', form='unformatted')
   write(100)m

   close(100)
end program

编译:

gfortran -o ttt.x -fconvert=big-endian ttt.f90

并执行:

./ttt.x

我编写了一个测试模块来读取 python 中的这个 big-endian 文件:

module test
   implicit none
   contains
   subroutine openFile(fileName)
      character(len=*), intent(in) :: fileName
      real(kind=4), allocatable :: array(:,:)

      print*,"open File:", trim(fileName)
      open(unit=100,file=trim(fileName),form='unformatted')

      allocate(array(2,2))
      read(100)array
      print*,array
   end subroutine openFile
end module test

使用 f2py 编译:

f2py -c -m test --f90flags='-fconvert=big-endian' test.f90

在 python 中加载测试模块:

from test import test as t

a=t.open(teste.bin)

结果是:

open File:fileTeste.bin
   1.15705214E-41   1.15705214E-41   1.15705214E-41   1.15705214E-41

那么,如何使用 f2py 读取大端文件?

谢谢 !

标签: pythonfortranf2py

解决方案


您可以使用 OPEN 语句的 CONVERT 说明符:

open(unit=100,file=trim(fileName),form='unformatted',convert='big_endian')

https://gcc.gnu.org/onlinedocs/gcc-11.2.0/gfortran/CONVERT-specifier.html

或设置环境变量 GFORTRAN_CONVERT_UNIT,见https://gcc.gnu.org/onlinedocs/gcc-11.2.0/gfortran/GFORTRAN_005fCONVERT_005fUNIT.html


推荐阅读