举个简单的例子:
在 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/