scala 执行外部命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16162483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute external command
提问by Khalid Saifullah
I do not know whether it is a Scala or Play! question. I want to execute some external command from my Play application, get the output from the command and show a report to user based on the command output. Can anyone help?
不知道是Scala还是Play!问题。我想从我的 Play 应用程序执行一些外部命令,从命令中获取输出并根据命令输出向用户显示报告。任何人都可以帮忙吗?
For example, when I enter my-commandfrom shell it shows output like below, which I want to capture and show in web:
例如,当我从 shell输入my-command 时,它显示如下输出,我想捕获并显示在 web 中:
Id Name IP
====================
1 A x.y.z.a
2 B p.q.r.s
Please, do not worry about format and parsing of the output. Functionally, I am looking something like PHP exec. I know about java Runtime.getRuntime().exec("command")but is there any Scala/Play version to serve the purpose?
请不要担心输出的格式和解析。在功能上,我看起来像 PHP exec。我知道 java Runtime.getRuntime().exec("command")但是否有任何 Scala/Play 版本可以达到此目的?
回答by Bj?rn Jacobs
You have to import the process packages of scala first. The method !!does what you need, it executes the statement and captures the text output.
必须先导入scala的流程包。方法!!做你需要的,它执行语句并捕获文本输出。
import scala.sys.process._
val cmd = "uname -a" // Your command
val output = cmd.!! // Captures the output
回答by Jamil
scala> import scala.sys.process._
scala> Process("cat temp.txt")!
This assumes there is a temp file in your home directory. !is for actual execution of the command. See scala.sys.process for more info.
这假设您的主目录中有一个临时文件。!用于实际执行命令。有关更多信息,请参阅 scala.sys.process。

