首页 > 解决方案 > 将命令行输出保存到 Fortran 中的变量

问题描述

有没有办法将命令行实用程序的输出存储到 Fortran 中的变量中?

我有一个基于 BASH 的实用程序,它给了我一个需要在 Fortran 程序中使用的数字。我想通过程序本身调用该实用程序,并尽可能避免将输出写入文件。

可能是这样的?

integer a
write(a,*) call execute_command_line('echo 5')

或者像这样?

read(call execute_command_line('echo 5'),*) a

我不认为这两个都是正确的。我想知道是否真的有一种方法可以做到这一点。我阅读了文档,execute_command_line但我认为执行此操作的子程序没有输出参数。

标签: fortrangfortran

解决方案


由于您使用的是 BASH,因此假设您正在使用某种类 unix 系统。所以你可以使用FIFO。就像是

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

请注意,FIFO 的 wrt 阻塞的语义可能有点棘手(这就是为什么在 echo 命令之后有 '&' 的原因,您可能需要稍微阅读一下并进行实验(特别是确保您没有获得无数当您多次执行此操作时,bash 进程会挂起)。


推荐阅读