How to execute (exec) external system commands in a Scala actor?

to run an external command, I have to

import sys.process._
val result="ls a" !

      

then when you are using an actor I need to use "!" send a message. So! is defined both in the actor and in the process, but I need to use them both in the same block of code, how to do this?

+1


source to share


2 answers


I see no problem Process

and ActorRef

defining a method with the same name.

An analog example:

class A { def ! = println("A") }
class B { def ! = println("B") }
val a = new A
val b = new B
a.! // "A"
b.! // "B"

      

There is no name clash or ambiguity at all.

The only thing you need to worry about is the implicit conversion from String

to Process

.



"foo".!

works because it Process

is the only class in which it String

can be implicitly converted to what the method defines !

.

As the documentation says, if you use something like "foo".lines

then the compiler gets confused because it doesn't know whether to convert String

to Process

or to StringLike

, since both define a lines

.

But - again - it's none of your business, and you can safely do something like:

"ls".!
sender ! "a message"

      

and the compiler shouldn't complain.

+2


source


The approach recommended for such cases seems to be just a process object of a process:

import scala.sys.process.Process
Process("find src -name *.scala -exec grep null {} ;") #| Process("xargs test -z") #&& Process("echo null-free") #|| Process("echo null detected") !

      



in your case:

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

      

-1


source







All Articles