【发布时间】:2017-08-19 08:51:07
【问题描述】:
我继承了一些看起来像这样的代码:
Python -> File -> Modern Fortran -> File -> Python
每个文件包含一个简单的实数数组。
我现在需要多次运行这个程序,而 I/O 让我很痛苦。我想省略文件并将 Python 输出读入 Fortran 并将 Fortran 输出读回 Python。
我可以通过从 Python 调用 Fortran 例程并将实数作为一系列字符串参数提供来省略第一个文件。
## This Python script converts a to a string and provides it as
## an argument to the Fortran script test_arg
import subprocess
a = 3.123456789
status = subprocess.call("./test_arg " + str(a), shell=True)
!! This Fortran script reads in a string argument provided by the
!! above Python script and converts it back to a real.
program test_arg
character(len=32) :: a_arg
real*8 :: a, b
call get_command_argument(1,a_arg)
read(a_arg,*), a
print*,a
b = a*10
end program test_arg
在不使用中间文件的情况下,将变量“b”输出到另一个 Python 脚本中的工作代码 sn-p 会是什么样子?
我读过关于 f2py 的文章,但是将继承的 Fortan 脚本转换为 Python 模块所涉及的重构量比我想做的要多。
【问题讨论】:
-
不要创建 Fortran 程序,创建一个子程序。或者创建一个子程序而不是主程序作为大部分 Fortran 代码的接口。
-
您可以让 fortran 将其输出写入标准输出(
write(*,*)b),您应该能够通过子进程读取结果。 fortran 需要“干净”,而不是向标准输出写入任何其他内容。 (其实集成代码比较好,不过这个很简单) -
我只是想补充一点,使用
shell = True会带来风险 -
谢谢。在调用fortran脚本的子进程命令下面,我可以放另一个从fortran的write(,)中读取stdout的子进程命令吗?您能否提供一个最低限度的工作示例?
-
从进程中读取:stackoverflow.com/q/2082850/1004168。要摆脱 shell,您将参数作为列表传递,而不是一个字符串。
标签: python python-3.x fortran