获取返回状态和程序输出

时间:2011-09-30 07:43:34

标签: lua

我需要使用Lua来运行一个二进制程序,它可以在stdout中写一些东西,并返回一个状态代码(也称为“exit status”)。

我在网上搜索过,找不到符合我需要的东西。但是我发现在Lua:

但是我需要两者。编写一个在场景后面运行两个函数的包装函数不是一个选项,因为进程开销和连续运行时结果可能会发生变化。我需要写一个这样的函数:

function run(binpath)
    ...
    return output,exitcode
end

有谁知道如何解决这个问题?

PS。目标系统响了Linux。

6 个答案:

答案 0 :(得分:10)

使用LUA 5.2我可以执行以下操作

-- This will open the file
local file = io.popen('dmesg')
-- This will read all of the output, as always
local output = file:read('*all')
-- This will get a table with some return stuff
-- rc[1] will be true, false or nil
-- rc[3] will be the signal
local rc = {file:close()}

希望这会有所帮助......

答案 1 :(得分:2)

此功能由C pclose提供。

  

成功返回后,pclose()将返回终止状态   命令语言解释器。

解释器返回其子节点的终止状态。

但是Lua没有做到这一点(io.close总是返回true)。我没有挖掘这些线索,但有些人抱怨这种脑损伤。

答案 2 :(得分:2)

我不能使用Lua 5.2,我使用这个辅助函数。

function execute_command(command)
    local tmpfile = '/tmp/lua_execute_tmp_file'
    local exit = os.execute(command .. ' > ' .. tmpfile .. ' 2> ' .. tmpfile .. '.err')

    local stdout_file = io.open(tmpfile)
    local stdout = stdout_file:read("*all")

    local stderr_file = io.open(tmpfile .. '.err')
    local stderr = stderr_file:read("*all")

    stdout_file:close()
    stderr_file:close()

    return exit, stdout, stderr
end

答案 3 :(得分:1)

如果您在Win32或POSIX环境中运行此代码,可以尝试使用此Lua扩展名:http://code.google.com/p/lua-ex-api/

或者,您可以编写一个小的shell脚本(假设bash或类似的可用):

  • 执行正确的可执行文件,将退出代码捕获到shell变量中,
  • 在标准输出
  • 上打印换行符和终端字符/字符串
  • 将shell变量值(退出代码)打印到标准输出

然后,捕获io.popen的所有输出并向后解析。

完全披露:我不是Lua的开发者。

答案 4 :(得分:0)

是的,os.execute()返回时你是对的,如果你明白如何用lua运行你的命令就很简单了 您也可能想知道它返回了多少变量,可能需要一段时间,但我认为您可以尝试

local a, b, c, d, e=os.execute(-what ever your command is-)

对于我的例子,a是第一个返回的参数,b是第二个返回的参数,等等。我想我根据你的要求正确回答了你的问题。

答案 5 :(得分:0)

这就是我的方法。

local process = io.popen('command; echo $?') -- echo return code of last run command
local lastline
for line in process:lines() do
    lastline = line
end
print(lastline) -- the return code is the last line of output