Execute external command

2019-02-08 12:45发布

问题:

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?

For example, when I enter my-command from shell it shows output like below, which I want to capture and show in 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?

回答1:

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.

import scala.sys.process._
val cmd = "uname -a" // Your command
val output = cmd.!! // Captures the output


回答2:

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.