将命令行输出保存到Fortran中的变量 [英] Save command line output to variable in Fortran

查看:93
本文介绍了将命令行输出保存到Fortran中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将命令行实用程序的输出存储到Fortran中的变量?

Is there a way to store the output of a command line utility to a variable in Fortran?

我有一个基于BASH的实用程序,该实用程序为我提供了一个需要在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.

也许是这样?

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

还是这样?

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

我认为这些都不对.我想知道实际上是否有一种方法可以做到这一点.我阅读了execute_command_line的文档,但我认为执行此操作的子例程没有输出参数.

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.

推荐答案

由于您正在使用BASH,因此假设您正在某种类似Unix的系统上工作.因此,您可以使用FIFO.像

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

请注意,FIFO的wrt阻塞的语义可能有些棘手(这就是在echo命令后加'&'的原因,您可能需要仔细阅读并进行试验(特别是确保没有)多次执行此操作时,会有不计其数的bash进程挂起.

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

这篇关于将命令行输出保存到Fortran中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆