我正在编写一个小的 Scala 脚本来为当前目录中的所有文件生成 PGP 签名。这是我写的:
object PGPSign {
def main(args: Array[String]) {
signFilesInDirectory(new java.io.File("."))
}
def signFilesInDirectory(dir: java.io.File) {
if(!dir.exists())
throw new java.io.FileNotFoundException
if(!dir.isDirectory())
throw new RuntimeException("Expecting directory")
println("Signing files in: " + dir.getAbsolutePath())
for{ file <- dir.listFiles
if !file.isDirectory //ignoring directories
val fileName = file.getName()
if !fileName.startsWith(".") //ignoring hidden files
} {
("gpg -ab " + fileName).!!
}
}
}
在控制台中,该命令gpg -ab FILE_NAME
将要求输入密码。当我执行我的 scala 脚本时,我在调用外部命令时遇到了这个异常:
gpg: cannot open tty `/dev/tty': Device not configured
Exception in thread "main" java.lang.RuntimeException: Nonzero exit value: 2
at scala.sys.package$.error(package.scala:27)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:131)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:101)
at PGPSign$$anonfun$signFilesInDirectory$3.apply(PGPSign.scala:25)
at PGPSign$$anonfun$signFilesInDirectory$3.apply(PGPSign.scala:20)
at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:743)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:34)
at scala.collection.mutable.ArrayOps.foreach(ArrayOps.scala:38)
at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:742)
at PGPSign$.signFilesInDirectory(PGPSign.scala:20)
at PGPSign$.main(PGPSign.scala:11)
at PGPSign.main(PGPSign.scala)
我认为这与外部命令(在本例中为 gpg)请求一些输入这一事实有关。如果这是造成问题的原因(?),从 Scala 执行时,使任何外部命令(请求任意数量的输入)工作的最简单的通用方法是什么?