Lua os.execute return value

核能气质少年 提交于 2020-01-11 17:09:09

问题


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: whatever is executed via the ox.execute and will return 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?


回答1:


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.




回答2:


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



回答3:


Lua's os.capture returns all standard output, thus it will be returned into that variable.

Example:

local result = os.capture("echo hallo")
print(result)

Printing:

hallo



回答4:


Sorry, but this is impossible. If the echo programm exit with success it will return 0. This returncode is what the os.execute() function get and returned too.

if  0 == os.execute("echo 'test'") then 
    local t = "test"
end

This is a way to get what you want, i hope it helps you.

Another Tip for getting the return code of a function is the Lua reference. Lua-Reference/Tutorial



来源:https://stackoverflow.com/questions/9676113/lua-os-execute-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!