Issuing native system commands in Scala

前端 未结 5 761
长情又很酷
长情又很酷 2021-02-01 16:42

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 is

相关标签:
5条回答
  • 2021-02-01 17:05

    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.

    0 讨论(0)
  • 2021-02-01 17:08

    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.

    0 讨论(0)
  • 2021-02-01 17:15

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

    0 讨论(0)
  • 2021-02-01 17:19
    import scala.sys.process._
    
    val vimLocation: String = "whereis vim" !!
    

    reference

    0 讨论(0)
  • 2021-02-01 17:22

    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.

    0 讨论(0)
提交回复
热议问题