18

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?

Khalid Saifullah
  • 747
  • 2
  • 8
  • 21
  • I thought of this idea: I need to clear the console, and well, `print("\u001b[2J")` doesn't work, it just moves the console forward over and over again when used; so I thought I would execute `clear` to clear the console without moving it! – RixTheTyrunt Jun 21 '22 at 16:37

3 Answers3

46

The method !! of the Scala process package does what you need, it executes the statement and captures the text output. For example:

import scala.sys.process._
val cmd = "uname -a" // Your command
val output = cmd.!! // Captures the output
mrucci
  • 4,342
  • 3
  • 33
  • 35
Björn Jacobs
  • 4,033
  • 4
  • 28
  • 47
7
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.

Jamil
  • 2,150
  • 1
  • 19
  • 20
-1

You can use the Process library: for instance

import scala.sys.process.Process
Process("ls").!!

to get the list of files in the folder as a string. The !! get the output of the command

Galuoises
  • 2,630
  • 24
  • 30