执行命令行并返回命令输出 [英] Execute command line and return command output

查看:205
本文介绍了执行命令行并返回命令输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使用非标准SYSTEM内部例程(类似于Fortran 2008 EXECUTE_COMMAND_LINE内部函数)从我的fortran程序中使用shell命令行调用:

  CALL SYSTEM(commandStr)

其中commandStr是包含shell命令的字符串我想执行。目前,我不知道直接返回commandStr的输出,但只返回它的返回状态。所以,我现在正在做的是将输出写入文件,然后从Fortran程序中读取文件。例子:

  CALL SYSTEM('sed''s /,// g''myFile> dummyFile')

如果我想从myFile中删除逗号。然后,我使用OPEN和READ来获取dummyFile的内容。



这很好,但我很关心从磁盘写入/读取文件,特别是当我这样做时在一个很长的循环内,如果commandStr输出很大。有没有办法将commandStr输出重定向到我可以直接从Fortran程序访问的内存缓冲区(非硬盘)?(可能通过特定的UNIT号码)?

popen()也可能是可用的。

  iunit = popen('sed''s /,// g''myFile','r')

查看Fortran环境的文档,因为我不确定将I / O连接到Fortran的语义。如果它类似于C运行时库,文件连接还需要一个特殊函数来关闭它, pclose()


Currently, I am using shell command line calls from my fortran program using non-standard SYSTEM intrinsic routine (similar to Fortran 2008 EXECUTE_COMMAND_LINE intrinsic):

CALL SYSTEM(commandStr)

where commandStr is a character string containing the shell command I want to execute. At the moment, I am not aware of a direct way to return the output of commandStr, but only its return status. So, what I am doing now is writing output into a file, and then reading the file from within the Fortran program. Example:

CALL SYSTEM('sed ''s/,//g'' myFile > dummyFile')

if I want to remove commas from myFile. I then use OPEN and READ to get contents of dummyFile.

This works just fine, however I am concerned about writing/reading files from disk, especially if I was doing this within a long loop, and if commandStr output was big. Is there a way to re-direct commandStr output into a memory buffer (not hard disk) which I could access from my Fortran program directly (maybe through a specific UNIT number)?

解决方案

If this is in a POSIX environment, the library function popen() might also be available.

iunit = popen ('sed ''s/,//g'' myFile', 'r')

Look at the documentation for your Fortran environment since I'm not sure of the semantics for connecting the i/o to Fortran. If it is like the C runtime library, the file connection also needs a special function to close it, pclose().

这篇关于执行命令行并返回命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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