Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute external command

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?

like image 639
Khalid Saifullah Avatar asked Apr 23 '13 06:04

Khalid Saifullah


People also ask

What is an external command in Python?

os. The subprocess module of Python's standard library has two functions meant for calling external commands. The purpose of functions in this module is to spawn a new process and connect to IO pipes. As per PEP 324, it is recommended to use the run() function to invoke a new process.

How do you run a command in subprocess in Python?

Running a Command with subprocess In the first line, we import the subprocess module, which is part of the Python standard library. We then use the subprocess. run() function to execute the command.


2 Answers

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
like image 100
Björn Jacobs Avatar answered Oct 24 '22 19:10

Björn Jacobs


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.

like image 28
Jamil Avatar answered Oct 24 '22 20:10

Jamil