[英]How do I return a console command as a String to a running software?
Let me give a simple example: 让我举一个简单的例子:
In a Linux environment I have a Grails script, and I want to get all my directories using ls command: 在Linux环境中,我具有Grails脚本,并且我想使用ls命令获取所有目录:
def ls = "ls".execute()
println ls
// result is java.lang.UNIXProcess@f16b42
Instead of getting the process ID, I want to get the same output I get into a terminal 我想要获取与终端相同的输出,而不是获取进程ID
Ps.: This is just a example, I don't really need to list directories. 附注:这只是一个例子,我真的不需要列出目录。
The quick way is: 快速的方法是:
String output = 'ls'.execute().text
println output
HOWEVER! 然而! If it writes a lot of output, the reader will fill up, and then it will all block.
如果写入大量输出,则读取器将填满,然后全部阻塞。 So, you need to do something like:
因此,您需要执行以下操作:
String output = new StringWriter().with { out ->
Process proc = 'ls'.execute()
proc.consumeProcessOutput( out, System.err )
proc.waitFor()
out.toString()
}
println output
Of course, you might want to check the exitCode that proc.waitFor()
returns, and do something better with the error stream then send it to System.err
, but you get the idea ;-) 当然,您可能想要检查
proc.waitFor()
返回的exitCode, proc.waitFor()
错误流进行更好的处理,然后将其发送到System.err
,但是您知道了;-)
You can also do something like this. 您也可以这样做。
File directory = new File(args[0])
Process p = "ls".execute([], directory)
p.waitForProcessOutput(System.out, System.err)
If this were a script called listFiles.groovy, you could run 如果这是一个名为listFiles.groovy的脚本,则可以运行
groovy listFiles ~/blah
and see everything in the blah directory. 并在blah目录中查看所有内容。 This is going to wait for the process to finish before moving onto any other commands.
这将等待过程完成,然后再移至其他任何命令。
Check out the groovy docs for Process . 查阅Process的常规文档。 There is a lot of fun stuff there.
那里有很多有趣的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.