Two Quick Nim Scripts

Today I Googled something like “julia lang compiled” for the umpteenth time in several months, and then I remembered that Nimrod existed, except it’s Nim these days, and it might make it to version 1.0 any week now. I decided to look around a bit, and I discovered that the documentation seems to have improved, and the language has gotten more fleshed out. I decided to try two small things I’ve been doing a lot of lately, SSH-ing and HTTP-getting and posting, and see what they look like in Nim.

HTTP Request

So, the first neat thing is that you can rename your modules with the as keyword the same way you can in Python. The next thing is that the httpclient.get() function performs a GET request, and then returns a tuple that I’ve named resp. The elements of this tuple can be retrieved using dot notation.

import httpclient as http
var resp = http.get( "http://apple.com" )
echo( resp.body )

Calling this as nim -r c get_example.nim will compile and run the code, returning the body of the HTML for apple.com.

System Commands, like SSH

I was also interested in running things from the command line. In this example I use a convenience function osproc.execCmdEx() that returns the output of the command and the exit code. In Python we’d have to fool with the subprocess module.

import osproc
var cmd = osproc.execCmdEx( "ssh remote ls" )
echo( cmd.output )
echo( cmd.exitCode )

Leave a Reply

Your email address will not be published. Required fields are marked *