python - 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 读取大端文件?
谢谢 !
解决方案
您可以使用 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
推荐阅读
- python - 为什么重塑我的数据会完全改变 Keras 中全连接神经网络的行为?
- javascript - 使用 Mongo Client 在身份验证模式下动态创建 Mongo DB 数据库
- python - 如何将抓取的 Web 数据保存到多个 csv 文件中
- javascript - Maps Javascript API 问题:“无法加载资源:net::ERR_CONNECTION_TIMED_OUT”
- wpf - 如何在此代码中将 contextMenu 放在按钮下?
- sql - 时间范围之间的PostgreSQL查询
- java - 没有得到半金字塔,而只是在java中得到一条直线
- c - 在 C 中出现分段错误,不知道为什么?
- vba - 如何点击 iframe 中的元素?
- javascript - 接受 KO 数字扩展中的小数位