2011-03-08 1617 views
11

我必须在Lua中使用io.popen来运行一个带有命令行参数的可执行文件。 如何等待一个过程在Lua中完成,以便可以捕获预期的输出?io.popen - 如何等待过程在Lua中完成?

local command = "C:\Program Files\XYZ.exe /all" 

    hOutput = io.popen(command) 
    print(string.format(""%s", hOutput)) 

假设可执行是XYZ.exe其需要与命令行参数/all被调用。

一旦io.popen(command)得到执行,进程将返回一些需要打印的字符串。

我的代码片段:

function capture(cmd, raw) 
    local f = assert(io.popen(cmd, 'r')) 
    -- wait(10000); 
    local s = assert(f:read('*a')) 
    Print(string.format("String: %s",s)) 
    f:close() 
    if raw then return s end 
    s = string.gsub(s, '^%s+', '') 
    s = string.gsub(s, '%s+$', '') 
    s = string.gsub(s, '[\n\r]+', ' ') 
    return s 
end 
local command = capture("C:\Tester.exe /all") 

您的帮助将不胜感激。

+0

我有一个代码,不知它不能正常工作 – Chet 2011-03-08 23:19:48

+0

功能捕获(CMD,原材料) 本地F =断言(io.popen(CMD, 'R')) - 等待(10000); 本地S =断言(六:读( '* A')) 打印(的String.Format( “字符串:%S”,S)) F:close()方法 如果原料然后再返回s结尾 S =串.gsub(s''%s +','') s = string.gsub(s,'%s + $','') s = string.gsub(s,'[\ n \ r] +' ,'') return s end local command = capture(“C:\ Tester.exe/all”) – Chet 2011-03-08 23:20:32

回答

18

如果你使用标准的Lua,你的代码看起来有点奇怪。我不完全确定有关超时或平台依赖关系的io.popen语义,但以下内容至少在我的机器上起作用。

local file = assert(io.popen('/bin/ls -la', 'r')) 
local output = file:read('*all') 
file:close() 
print(output) --> Prints the output of the command.