运行进程时出现IOException

时间:2016-12-01 16:14:19

标签: scala

假设:

$pwd
/home/kmeredith/src/linux_sandbox
$ls a.txt 
a.txt
$cat a.txt 

$

然后我试图运行一个scala.sys.process.Process,它会附加' hi'到a.txt

import scala.sys.process._
import java.io.File

scala> Process( List("echo 'hi' >> a.txt"), new File(".") )
res3: scala.sys.process.ProcessBuilder = [echo 'hi' > a.txt]

scala> res3.!
java.io.IOException: Cannot run program "echo 'hi' > a.txt" (in directory "."): error=2, No such file or directory
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
  at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:69)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:98)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:112)
  ... 32 elided
Caused by: java.io.IOException: error=2, No such file or directory
  at java.lang.UNIXProcess.forkAndExec(Native Method)
  at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
  at java.lang.ProcessImpl.start(ProcessImpl.java:134)
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
  ... 35 more

请注意,当我提供完整路径时它也失败了:

scala> Process( List("echo 'hi' > a.txt"), new File("/home/kmeredith/src/linux_sandbox") )
res0: scala.sys.process.ProcessBuilder = [echo 'hi' > a.txt]

为什么我会看到此错误?

scala> res0.!
java.io.IOException: Cannot run program "echo 'hi' > a.txt" (in directory "/home/kmeredith/src/linux_sandbox"): error=2, No such file or directory
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
  at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:69)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:98)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:112)
  ... 32 elided
Caused by: java.io.IOException: error=2, No such file or directory
  at java.lang.UNIXProcess.forkAndExec(Native Method)
  at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
  at java.lang.ProcessImpl.start(ProcessImpl.java:134)
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
  ... 35 more

1 个答案:

答案 0 :(得分:1)

您可以使用ProcessBuilder DSL重定向输出:

Seq("echo", "some text") #>> new File("a.txt")

此处Seq[String]将隐式转换为ProcessBuilderSeq的每个元素都将被视为命令的参数(第一个元素echo)并正确转义,因此您不需要任何额外的引用(并且不应该放>>那里)。

作为第二个参数传递的文件是cwd(当前工作目录),因此在这种特殊情况下它不会更改任何内容。请参阅sys.process docs的“处理输入和输出”部分。