简体   繁体   中英

How do I read Fortran output into Python?

I inherited some code that looks like this:

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

where each File contains a simple array of reals.

I now need to run this program many times and the I/O is hurting me. I want to omit the files and read the Python output into Fortran and read the Fortran output back into Python.

I can omit the first file by calling the Fortran routine from Python and providing the reals as a series of string arguments.

## 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

What would a working code snippet look like to output the variable 'b' into another Python script without using an intermediate file?

I've read about f2py, but the amount of refactoring involved in turning the inherited Fortan scripts into Python modules is more than what I want to do.

If you could rebuild the Fortran code as a library, you could use that from Python using in several ways.

I've found that what suits my needs is the following:

## 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM