Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get back the output of os.execute in Lua

Tags:

lua

When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?

like image 397
Drealmer Avatar asked Sep 25 '08 09:09

Drealmer


People also ask

What does OS execute do Lua?

The Lua os. execute() function can be used to run an external program from SIMION. The Lua io. popen() function is similar but captures any data written to standard output as a string (or writes a string to standard input).

How do I run a shell command in Lua?

Every shell command can be invoked as a Lua function. For example, calling echo hello world in Lua would be echo('Hello', 'world') . To achieve this I added a handler function for the missing table items in the globals table.


2 Answers

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.)

like image 114
2 revs Avatar answered Oct 21 '22 19:10

2 revs


I think you want this http://pgl.yoyo.org/luai/i/io.popen io.popen. But it's not always compiled in.

like image 21
Arle Nadja Avatar answered Oct 21 '22 17:10

Arle Nadja