[关闭]
@xtccc 2017-09-11T23:57:34.000000Z 字数 1599 阅读 3815

执行Shell Command / Scripts

给我写信
GitHub

此处输入图片的描述

Scala




可以在Scala中直接运行外部的shell命令,或者shell脚本,并且可以拿到执行的结果/输出;此外,还可以实现pipeline。


参考:

  1. How to execute external system commands in Scala
  2. Building a Pipeline of Commands


Solution

To execute external commands, use the methods of the scala.sys.process package. There are three primary ways to execute external commands:

  1. Use the ! method to execute the command and get its exit status.
  2. Use the !! method to execute the command and get its output.
  3. Use the lines method to execute the command in the background and get its result as a Stream.



1. 执行 command


  1. # 被执行脚本
  2. echo "hello"
  3. echo "hi"
  4. sleep 3s # 睡眠3秒
  5. exit 96
  1. // Scala程序
  2. import sys.process._
  3. val script = "/Users/tao/Downloads/test.sh"
  4. println("开始")
  5. val ret: Int = s"$script"! // ret是script的返回值
  6. // 这里必须有一个空行,否则会有编译错误
  7. println(s"返回值 = $ret") // 返回96



关于 !的源码

  1. /** Starts the process represented by this builder, blocks until it exits, and
  2. * returns the exit code. Standard output and error are sent to the given
  3. * ProcessLogger.
  4. */
  5. def !(log: ProcessLogger): Int



!来执行script时,将会是blocking的模式:即等到script完成之后,scala代码才会继续往下执行。



2. 将输出重定向到文件


  1. import sys.process._
  2. val script = "/Users/tao/Downloads/test.sh"
  3. println("开始")
  4. val ret: Int = (s"$script" #>> new File("log"))!
  5. println(s"返回值 = $ret")

script的输出内容将被重定向到文件"log"中


3. 获取输出内容


!!来实现


也可以同时获取return code, stdout, stderr:
Scala: How to handle the STDOUT and STDERR of external commands

  1. val stdout = new StringBuilder()
  2. val stderr = new StringBuilder()
  3. val status = cmd ! ProcessLogger(stdout append _, stderr append _)
  4. logger.info(s"status = $status")
  5. logger.info(s"stdout = $stdout")
  6. logger.info(s"stderr = $stderr")

4. pipeline




5. AKKA带来的!二义性


如果同一个文件中也引用了AKKA的包,那么由于AKKA使用符号!来发送消息,就会产生二义性。
解决方法是:

  1. val cmd = "xxx xxxx"
  2. val ret = sys.process.Process(cmd).!
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注