Kevin Meredith
Kevin Meredith

Reputation: 41909

IOException When Running Process

Given:

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

$

I then tried to run a scala.sys.process.Process that would append 'hi' to 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

Note that it also failed when I gave the full path:

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

Why am I seeing this error?

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

Upvotes: 0

Views: 659

Answers (1)

laughedelic
laughedelic

Reputation: 6460

You can use ProcessBuilder DSL for redirecting the output:

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

Here Seq[String] will be implicitly converted to ProcessBuilder. Each element of the Seq will be treated as an argument of the command (first element echo) and properly escaped, so you don't need any extra quoting (and shouldn't put >> there).

The file that you pass as the second argument is the cwd (current working directory), so in this particular case it doesn't change anything. See "Handling Input and Output" section of the sys.process docs.

Upvotes: 1

Related Questions