相关文章推荐
有情有义的大白菜  ·  python ...·  1 月前    · 
完美的馒头  ·  python QTreeWidget ...·  4 周前    · 
失眠的烤红薯  ·  python qt textBrowser ...·  3 周前    · 
帅气的领带  ·  【Pyspark ...·  1 周前    · 
近视的橙子  ·  python ...·  1 周前    · 
乐观的皮带  ·  pytorch推理 ...·  5 月前    · 
追风的炒粉  ·  SQLite ...·  1 年前    · 

f2py:如何在python中打开和读取用fortran编写的字节交换(big-endian)文件的库?

0 人关注

我有一个文件是以big-endian格式写入的。我写了一个库来访问这个文件。现在我试图用这个库在一个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

to compile:

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

我写了一个测试模块,在python中读取这个大-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

compile using 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读取一个big-endian文件?

5 个评论
我从来不喜欢这些转换选项。我认为自己转换字节顺序要好得多。我们有一些关于这个问题的Fortran问题。你也可以在Python中这样做 stackoverflow.com/questions/27506474/... (第一次搜索命中,我没有看答案)。
@VladimirF,是的,python方式。 struct.unpack("<f", struct.pack(">f", 1.15705214E-41 ))[0] 返回 10.0 ,反之亦然。
@VladimirF, 我也不喜欢这样,但我使用的是大气模型,它的文件是以光谱形式写成的大-endian格式。所以,我的库读取这些文件,从光谱空间转换为网格空间,然后 "发送 "给python。也许我会写一段代码来转换字节顺序,我想这是最好的方法...... 谢谢你的建议!
@Serge3leo 这个选项的问题是,我需要在fortran中使用矩阵,在发送至python之前做一些数学运算。也谢谢你的建议!
正如我所写的,这个网站上已经有了一些例子,如 stackoverflow.com/questions/30061362/... 或我给出的我的模块的链接,在 stackoverflow.com/questions/68931014/...
python
fortran
f2py
João Gerd Zell de Mattos
João Gerd Zell de Mattos
发布于 2021-11-12
1 个回答
Serge3leo
Serge3leo
发布于 2021-11-12
已采纳
0 人赞同