将命令行输出保存到 Fortran 中的变量
Save command line output to variable in 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
的文档,但我认为执行此操作的子例程没有输出参数。
由于您使用的是 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 的阻塞语义可能有点棘手(这就是为什么在 echo 命令后有 '&' 的原因,您可能想稍微阅读一下并进行实验(特别是确保您没有当您多次执行此操作时,会有无数 bash 个进程闲置。
有没有办法将命令行实用程序的输出存储到 Fortran 中的变量?
我有一个基于 BASH 的实用程序,它为我提供了一个需要在 Fortran 程序中使用的数字。我想通过程序本身调用该实用程序,并尽可能避免将输出写入文件。
也许是这样的?
integer a
write(a,*) call execute_command_line('echo 5')
或者像这样?
read(call execute_command_line('echo 5'),*) a
我认为这两个都不对。我想知道是否真的有一种方法可以做到这一点。我阅读了 execute_command_line
的文档,但我认为执行此操作的子例程没有输出参数。
由于您使用的是 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 的阻塞语义可能有点棘手(这就是为什么在 echo 命令后有 '&' 的原因,您可能想稍微阅读一下并进行实验(特别是确保您没有当您多次执行此操作时,会有无数 bash 个进程闲置。