问题
Is there a way to store the output of a command line utility to a variable in Fortran?
I have a BASH based utility which gives me a number which needs to be used in a Fortran program. I want to call the utility through the program itself, and avoid writing the output to a file if possible.
Something like this maybe?
integer a
write(a,*) call execute_command_line('echo 5')
Or like this maybe?
read(call execute_command_line('echo 5'),*) a
I don't think either of these is right though. I would like to know if there is actually a method to do this. I read the docs for execute_command_line
but I don't think there is an output argument for the subroutine which does this.
回答1:
Since you're using BASH, lets assume you're working on some kind of unix-like system. So you could use a FIFO. Something like
program readfifo
implicit none
integer :: u, i
logical :: ex
inquire(exist=ex, file='foo')
if (.not. ex) then
call execute_command_line ("mkfifo foo")
end if
call execute_command_line ("echo 5 > foo&")
open(newunit=u, file='foo', action='read')
read(u, *) i
write(*, *) 'Managed to read the value ', i
end program readfifo
Note that the semantics of FIFO's wrt blocking can be a bit tricky (that's why there is the '&' after the echo command, you might want to read up on it a bit and experiment (particularly make sure you haven't got a zillion bash processes hanging around when you do this multiple times).
来源:https://stackoverflow.com/questions/53447665/save-command-line-output-to-variable-in-fortran