Lua os.execute 返回值

问题描述 投票:0回答:5

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

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

我只是想实现这个:每当

os.execute
返回任何值时,我想在Lua中使用它 - 例如
echo 'test'
将在bash命令行中输出
test
- 是否有可能获得返回值(
test
在这种情况下)到 Lua 局部变量?

lua shellexecute
5个回答
114
投票

您可以改用

io.popen()
。这将返回一个文件句柄,您可以使用它来读取命令的输出。像下面这样的东西可能会起作用:

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

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


4
投票
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

0
投票

如果您的系统支持,

io.popen
os.execute
更适合此用例。后者只返回退出状态而不是输出。

-- runs command on a sub-process.
local handle = io.popen('cmd')
-- reads command output.
local output = handle:read('*a')
-- replaces any newline with a space
local format = output:gsub('[\n\r]', ' ')

工作示例:

local handle = io.popen('date +"%T.%6N"')
local output = handle:read('*a')
local time = output:gsub('[\n\r]', ' ')
handle:close()
print(time .. 'DEBUG: Time recorded when this event happened.')

-6
投票

Lua 的

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

例子:

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

印刷:

hallo

-20
投票

对不起, 但这是不可能的。 如果 echo 程序成功退出,它将返回 0。这个返回码是 os.execute() 函数得到并返回的。

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

这是一个得到你想要的东西的方法,我希望它能帮助到你。

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

© www.soinside.com 2019 - 2024. All rights reserved.