如何将Fortran输出读入Python?

时间:2017-03-26 18:41:40

标签: python python-3.x fortran

我继承了一些看起来像这样的代码:

Python -> File -> Modern Fortran -> File -> Python

其中每个文件包含一个简单的实数数组。

我现在需要多次运行此程序,I / O会伤害我。我想省略文件并将Python输出读入Fortran并将Fortran输出读回Python。

我可以通过从Python调用Fortran例程并将reals作为一系列字符串参数来省略第一个文件。

## 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脚本中的工作代码片段是什么样的?

我已经阅读了关于f2py的内容,但是将继承的Fortan脚本转换为Python模块所涉及的重构量超出了我想要做的次数。

2 个答案:

答案 0 :(得分:0)

如果您可以将Fortran代码重建为库,则可以通过多种方式使用Python中的代码。

答案 1 :(得分:0)

我发现符合我需求的是:

## Sends a0 as a string to fortran script.
## Receives stdout from fortran, decodes it from binary to ascii,
## splits up values, and converts to a numpy array.

from subprocess import *
from decimal import Decimal as Dec

a0 = 3.123456789

proc = subprocess.Popen(["./test_arg", str(Dec(a0))], stdout=subprocess.PIPE)
out, err= proc.communicate()
result = np.array(out.decode('ascii').split(), dtype=float)