03
Sep
11

scala process output


At one point or another, we all want to execute an external process from our scripts, capture it’s output in a variable, and do something with it. In typical scripting languages, this operation is very painless. Take Ruby, for example:


dir_output = `cmd.exe /c dir`


This would execute the dir command, and store it's output in the dir_output variable. dir_output's class is String.

As it turns out, it's not very difficult to achieve the same thing in Scala.


import tools.nsc.io._

val dirOutput = Process("cmd.exe /c dir").stdout.collect { case line:String => line }
dirOutput.foreach(println)

In this case, we're executing the same dir command, and we're iterating over the standard output, collecting the results. The type of the dirOutput is going to be Iterable[String], which allows for all that iterator goodness we're all used to.

Even though in most cases, this is enough to get your work done, it's good practice to check for a process's exit code, and it's standard error stream. Take the following example:


import tools.nsc.io._

val dirProc = Process("camd.exe /c dir")
val stdOut  = dirProc.stdout.collect { case line:String => line }
val stdErr  = dirProc.stderr.collect { case line:String => line }

println("STDOUT:")
println(stdOut.mkString("
"))
println("END OF STDOUT:")

println("STDERR:")
println(stdErr.mkString("\n"))
println("END OF STDERR")

println(dirProc.exitValue)
dirProc.destroy

As you can notice, I have a typo in the above snippet. I am executing camd.exe instead of cmd.exe, and unless you magically have a binary named camd.exe which accepts a /c flag, the process would most likely exit with an error code different than 0.

To access the process's exit code, we use the exitValue method. Because this method returns an Option[Int], you'd see this as output:


Some(1)

Here's how you'd find out the actual code of the process:


println(dirProc.exitValue match {
	case Some(value) => value match {
		case 0 => "success"
		case _ => "failure"
	}
	case _ => "thread exception?"
})

Any code different than 0 means failure. If the exitValue returns None, it probably means that an exception occured, probably an IllegalThreadStateException, as documented in the JDK doc.

I'd say working with a process in Scala is quite pleasant. Wouldn't you? 🙂

Advertisements

0 Responses to “scala process output”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Blog Stats

  • 222,570 hits

%d bloggers like this: