Nim: Executing external commands

Nim: Executing external commands

One fairly unique aspect of executing commands that Nim has, that I’ve not experienced anywhere else, is staticExec. It allows a process to be executed at compile time, and the results at that specific moment included in the build in some way. An example from the docs is to interrogate the current environment to tag the current git status and OS architectures:

// Runs at compile time
const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
                  "\nCompiled on " & staticExec("uname -v")

To execute a process and return the results to a variable:

let output = execProcess("nim", args=["c", "-r", "hellowworld.nim"])

If you just want the exit status:

import osproc
let output = execCmd("blerk")
echo output
# sh: blerk: not found
# 127

Or if you want exit status and output:

import osproc

let (output, status) = execCmdEx("ls -a")
echo status
# 0
echo output
# . ..

If you need to get more control then startProcess is the lower level function to call. The execProcess function earlier was just a convenience function to make common usage simpler. Make sure to close the process when you’re done:

import osproc, strutils, streams

let process = startProcess("some-interactive-process", args = ["-v"],
  options = {poInteractive, poUsePath})
let (fromp, top) = (process.outputStream, process.inputStream)

top.write "repeat this please\n"
top.flush
echo fromp.readLine.toUpper

top.write "and this\n"
top.flush
echo fromp.readLine.toUpper

discard process.waitForExit
process.close

Published: 21/03/2022

Hi, I'm Glenn! 👋

I've spent most of my career working with or at startups. I'm currently the VP of Product / GTM @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform 1.0, Terraform Cloud, and a whole host of amazing capabilities that set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.