Issuing native system commands in Scala

百般思念 提交于 2019-12-20 09:45:50

问题


I want to issue a native system command from a Scala program, and perhaps trap the output. ("ls" comes to mind. There may be other ways to get directory information without issuing the command, but that's beside the point of my question.) It would correspond to os.system(...) in Python.

I've looked in "Programming in Scala". I've looked in O'Reilly's "Programming Scala". I've Googled several combinations of terms. No luck yet. Can someone out there give me an example, or point me at a resource where I can find an example?


回答1:


Best way to do that is to use scala.sys.process.




回答2:


import scala.sys.process._

val vimLocation: String = "whereis vim" !!

reference




回答3:


Scala is not different from Java in this area, since you can call any Java API functions using Scala's interop features. See for example, java.lang.ProcessBuilder.




回答4:


You can do it using sys.process easily:

Executing system commands and getting their status code (exit code):

import sys.process._

val result = "your_command" !
println("result = "+result) // result contain zero for success or non zero for fail

Getting output from system commands:

import sys.process._

val result = "your_command" !!
println("result = "+result) // result contain output from the command

You have several other options (pipeline, Redirect STDOUT, Append to STDOUT and ...), you can see this link.




回答5:


Scala has complete interoperability with Java. So you can call the system commands from Scala as you would from Java. See this to see how to call system commands from Java.



来源:https://stackoverflow.com/questions/3064994/issuing-native-system-commands-in-scala

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