从 Scala 应用程序执行 shell 脚本 [英] Execute shell script from scala application

查看:47
本文介绍了从 Scala 应用程序执行 shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Scala 应用程序执行 sh 文件.假设我有 createPassword.sh 文件,我需要从 Scala 应用程序调用这个 sh 文件并取回输出.

I want to execute the sh file from Scala application. Let's say I have createPassword.sh file and I need to invoke this sh file from Scala application and get the output back.

如何通过scala应用实现?

How can I achieve through scala application?

推荐答案

如果脚本在当前工作目录中(否则指定脚本的完整路径)

This should do the trick if the script is in the current working directory (otherwise specify the full path of the script)

import sys.process._
val result = "./createPassword.sh" !!

result 然后是一个包含标准输出(和标准错误)的字符串

result is then a String containing the standard output (and standard error)

如果您想使用 Java SE7 中的 ProcessBuillder,您也可以在 Scala 中使用它:

If you want to use ProcessBuillder from Java SE7, you can also use this in scala:

  import java.io.{BufferedReader, InputStreamReader}

  val p = new ProcessBuilder("/bin/bash","createPassword.sh")
  val p2 = p.start()
  val br = new BufferedReader(new InputStreamReader(p2.getInputStream()))

  var line:String = ""
  while ({line = br.readLine();  line!= null}) {
    println(line)
  }

这篇关于从 Scala 应用程序执行 shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆