Run shell commands in Scala code on Windows seems

2019-04-07 11:49发布

When I try to run shell commands on Mac, it worked as expected like this:

scala> import scala.sys.process._
import scala.sys.process._

scala> """protractor --version"""!
warning: there were 1 feature warning(s); re-run with -feature for details
Version 0.24.0
res12: Int = 0

scala>

But if I do it on Windows, I get this:

scala> import scala.sys.process._
import scala.sys.process._

scala> """protractor --version"""!
warning: there were 1 feature warning(s); re-run with -feature for details
java.io.IOException: Cannot run program "protractor": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)

It seems like I have to do it like this on Windows:

scala> import scala.sys.process._
scala> """C:\Users\twer\AppData\Roaming\npm\protractor.cmd --version"""!
warning: there were 1 feature warning(s); re-run with -feature for details
Version 0.24.0
res11: Int = 0

scala>

I have to supply the full absolute path of the command.

But I am certain that the command is available in the path.

Is there anyway to avoid this?

1条回答
Fickle 薄情
2楼-- · 2019-04-07 12:40

You could try this:

val command = Seq("protractor", "--version")
val os = sys.props("os.name").toLowerCase
val panderToWindows = os match {
  case x if x contains "windows" => Seq("cmd", "/C") ++ command
  case _ => command
}
panderToWindows.!
查看更多
登录 后发表回答