linux - 如何将控制台命令作为字符串返回给正在运行的软件?

标签 linux shell grails groovy terminal

举个简单的例子:
在 Linux 环境中,我有一个 Grails 脚本,我想使用 ls 命令获取我的所有目录:

def ls = "ls".execute()
println ls
// result is java.lang.UNIXProcess@f16b42

我不想获取进程 ID,而是想获取与终端相同的输出

Ps.: 这只是一个例子,我真的不需要列出目录。

最佳答案

快速的方法是:

String output = 'ls'.execute().text
println output

然而!如果它写了很多输出,读者就会填满,然后它就会全部阻塞。因此,您需要执行以下操作:

String output = new StringWriter().with { out ->
    Process proc = 'ls'.execute()
    proc.consumeProcessOutput( out, System.err )
    proc.waitFor()
    out.toString()
}
println output

当然,您可能想检查 proc.waitFor() 返回的 exitCode,并对错误流做一些更好的处理,然后将其发送到 System.err , 但你明白了 ;-)

关于linux - 如何将控制台命令作为字符串返回给正在运行的软件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13608243/

相关文章:

linux - 为什么套接字连接被阻塞,TCP 内核不断重传 [ACK] 数据包

linux - 使用 bash 脚本使用 valgrind 检查内存

android - 在 app.json 中定义 expo entryPoint 不起作用

Grails - 查询域实例的属性

javascript - 如何通过定时调用remoteFunction从controller获取数据?

python - 在 python2.7 上安装 libxml 预构建二进制文件

linux - awk 没有按预期工作

linux - Puppet 总是将文件解压缩到只读文件夹中

linux - bash 中的脚本等待进程然后放弃

hibernate - Grails将域类映射到oracle数据库中已经存在的 View