Get back the output of os.execute in Lua
If you have io.popen, then this is what I use:
function os.capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end
If you don't have io.popen, then presumably popen(3) is not available on your system, and you're in deep yoghurt. But all unix/mac/windows Lua ports will have io.popen.
(The gsub
business strips off leading and trailing spaces and turns newlines into spaces, which is roughly what the shell does with its $(...)
syntax.)
I think you want this http://pgl.yoyo.org/luai/i/io.popen io.popen. But it's not always compiled in.
I don't know about Lua specifically but you can generally run a command as:
comd >comd.txt 2>&1
to capture the output and error to the file comd.txt, then use the languages file I/O functions to read it in.
That's how I'd do it if the language itself didn't provide for capturing stanard output and error.