2011-03-08 1618 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.