简体   繁体   English

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

[英]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.

相关问题 运行nohup命令后如何查看输出控制台? - How can I see the output console after running a nohup command? 如何在登录时运行命令并将其显示在控制台中? - How do I run a command on login and have it appear in the console? 如何使用python命中此命令并返回结果? - How do I use python to hit this command and return the result? 使用yum install命令时如何获取软件版本? - How to get the version of the software when I use yum install command? 如何修复此SED命令以查找和替换字符串 - How Do I Fix This SED Command to Find & Replace a String 如何在二进制文件中找到字符串? (不,不是strings命令。) - How do I locate a string in a binary file? (No, not the strings command.) 我如何#include <termios.h> 在Arduino软件(1.6.5)中? - How do I #include <termios.h> in the Arduino Software (1.6.5)? 使用sudo在单个命令中运行“我是谁”不会返回任何内容 - Running “who am i” in a single command with sudo doesnt return anything 如何根据在该文件上运行的命令输出的内容搜索文件 - How do I search for a file based on what is output by a command running on that file 如何在“top”linux命令中进行控制台输入? - How to do console input like in the “top” linux command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM