The Scala Toolkit

How to run a process?

Language

You can require the entire toolkit in a single line:

//> using toolkit latest

Alternatively, you can require just a specific version of OS-Lib:

//> using dep com.lihaoyi::os-lib:0.9.1

In your build.sbt, you can add a dependency on the toolkit:

lazy val example = project.in(file("example"))
  .settings(
    scalaVersion := "3.2.2",
    libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
  )

Alternatively, you can require just a specific version of OS-Lib:

libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.9.1"

In your build.sc file, you can add a dependency on the Toolkit:

object example extends ScalaModule {
  def scalaVersion = "3.2.2"
  def ivyDeps =
    Agg(
      ivy"org.scala-lang::toolkit:0.1.7"
    )
}

Alternatively, you can require just a specific version of OS-Lib:

ivy"com.lihaoyi::os-lib:0.9.1"

Starting an external process

To set up a process, use os.proc, then to actually start it, call():

val path: os.Path = os.pwd / "output.txt"
println(os.exists(path))
// prints: false
val result: os.CommandResult = os.proc("touch", path).call()
println(result.exitCode)
// prints: 0
println(os.exists(path))
// prints: true

Note that proc accepts both strings and os.Paths.

Reading the output of a process

(The particular commands in the following examples might not exist on all machines.)

Above we saw that call() returned an os.CommandResult. We can access the result’s entire output with out.text(), or as lines with out.lines().

For example, we could use bc to do some math for us:

val res: os.CommandResult = os.proc("bc", "-e", "2 + 2").call()
val text: String = res.out.text()
println(text.trim.toInt)
// prints: 4

Or have cal show us a calendar:

val res: os.CommandResult = os.proc("cal", "-h", "2", "2023").call()
res.out.lines().foreach(println)
// prints:
//   February 2023
// Su Mo Tu We Th Fr Sa
//          1  2  3  4
// ...

Customizing the process

call() takes various optional arguments, too many to explain individually here. For example, you can set the working directory (cwd = ...), set environment variables (env = ...), or redirect input and output (stdin = ..., stdout = ..., stderr = ...). Find more information about the call method on the README of OS-Lib.

Contributors to this page: