@xtccc
2017-09-11T23:57:34.000000Z
字数 1599
阅读 3815
Scala
可以在Scala中直接运行外部的shell命令,或者shell脚本,并且可以拿到执行的结果/输出;此外,还可以实现pipeline。
参考:
Solution
To execute external commands, use the methods of the scala.sys.process package. There are three primary ways to execute external commands:
- Use the
!
method to execute the command and get its exit status.- Use the
!!
method to execute the command and get its output.- Use the
lines
method to execute the command in the background and get its result as a Stream.
# 被执行脚本
echo "hello"
echo "hi"
sleep 3s # 睡眠3秒
exit 96
// Scala程序
import sys.process._
val script = "/Users/tao/Downloads/test.sh"
println("开始")
val ret: Int = s"$script"! // ret是script的返回值
// 这里必须有一个空行,否则会有编译错误
println(s"返回值 = $ret") // 返回96
关于 !
的源码
/** Starts the process represented by this builder, blocks until it exits, and
* returns the exit code. Standard output and error are sent to the given
* ProcessLogger.
*/
def !(log: ProcessLogger): Int
用!
来执行script时,将会是blocking的模式:即等到script完成之后,scala代码才会继续往下执行。
import sys.process._
val script = "/Users/tao/Downloads/test.sh"
println("开始")
val ret: Int = (s"$script" #>> new File("log"))!
println(s"返回值 = $ret")
script的输出内容将被重定向到文件"log"中
用!!
来实现
也可以同时获取return code, stdout, stderr:
Scala: How to handle the STDOUT and STDERR of external commands
val stdout = new StringBuilder()
val stderr = new StringBuilder()
val status = cmd ! ProcessLogger(stdout append _, stderr append _)
logger.info(s"status = $status")
logger.info(s"stdout = $stdout")
logger.info(s"stderr = $stderr")
如果同一个文件中也引用了AKKA的包,那么由于AKKA使用符号!
来发送消息,就会产生二义性。
解决方法是:
val cmd = "xxx xxxx"
val ret = sys.process.Process(cmd).!