Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua os.execute return value

Is it possible to read the following from the local variable in Lua?

local t = os.execute("echo 'test'") print(t) 

I just want to achieve this: whenever os.execute returns any value, I would like to use it in Lua - for example echo 'test' will output test in the bash command line - is that possible to get the returned value (test in this case) to the Lua local variable?

like image 881
Cyclone Avatar asked Mar 12 '12 23:03

Cyclone


People also ask

What is OS execute in 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). API details on these functions are in the Lua Reference Manual.

How do I set environment variables in Lua?

If you want to affect the lua process's environment (which would then, in turn, affect the environment's of processes run by lua) then you need a binding to the setenv system function (which lua itself doesn't provide as it doesn't pass the clean C test that lua uses for things it includes).

How do I run a shell command in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.


2 Answers

You can use io.popen() instead. This returns a file handle you can use to read the output of the command. Something like the following may work:

local handle = io.popen(command) local result = handle:read("*a") handle:close() 

Note that this will include the trailing newline (if any) that the command emits.

like image 140
Lily Ballard Avatar answered Oct 03 '22 01:10

Lily Ballard


function GetFiles(mask)    local files = {}    local tmpfile = '/tmp/stmp.txt'    os.execute('ls -1 '..mask..' > '..tmpfile)    local f = io.open(tmpfile)    if not f then return files end      local k = 1    for line in f:lines() do       files[k] = line       k = k + 1    end    f:close()    return files  end 
like image 39
rhomobi Avatar answered Oct 03 '22 00:10

rhomobi