关于shellexecute:Lua os.execute返回值

Lua os.execute return value

是否可以从Lua中的局部变量读取以下内容?

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

我只是想实现:通过ox.execute执行的任何操作都将返回任何值,我想在Lua中使用它-例如echo 'test'将在bash命令行中输出test-是能否将返回值(在这种情况下为test)获取到Lua局部变量?


您可以改用io.popen()。这将返回一个文件句柄,您可以使用该文件句柄来读取命令的输出。类似以下内容可能会起作用:

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

请注意,这将包括命令发出的尾随换行符(如果有)。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

Lua \\的os.capture返回所有标准输出,因此它将被返回到该变量中。

示例:

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

打印:

1
hallo


对不起,
但这是不可能的。
如果echo程序成功退出,它将返回0。此返回码也是os.execute()函数获取并返回的内容。

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

这是一种获取您想要的东西的方法,希望对您有所帮助。

获取函数返回代码的另一个技巧是Lua参考。
Lua参考/教程