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

社会主义新天地 提交于 2019-12-08 04:21:49

问题


to run an external command, I should

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

then when use actor, I need to also use "!" to send message. So ! is defined both in actor and in process, but I need to use them both in the same code block, how to do that?


回答1:


I don't see the issue of Process and ActorRef both defining a method with the same name.

An analog example would be

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

There's no name collision or ambiguity at all.

The only thing you have to worry about is the implicit conversion from String to Process.

"foo".! works because Process is the only class in which String can implicitly be converted to that defines a ! method.

As the documentation says, if you instead use something like "foo".lines, then the compiler gets confuse because it doesn't know whether to convert String to Process or to StringLike, since both define a lines method.

But - again - this is not your case, and you can safely do something like:

"ls".!
sender ! "a message"

and the compiler should not complain.




回答2:


The recommended approach for such cases seems to be import Process object only:

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")


来源:https://stackoverflow.com/questions/25339624/how-to-execute-exec-external-system-commands-in-scala-actor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!