2012-01-12 64 views
3

在我的Lua程序中,我必須捕獲來自外部程序的輸出。這個外部程序需要某些環境變量。所以我這樣做:與環境調用popen

e = "" 
e = e .. "A=100;" 
e = e .. "B=Hi;" 
e = e .. "C=Test;" 
file = io.popen(e .. "/bin/aprogr") 

顯然論據POPEN()可以通過限制(如果有的話),如果環境是很大的。

是否有任何其他方式將環境傳遞給外部程序?

回答

4

ExtensionProposal API中有os.spawn函數。

可以按如下方式使用它:

require"ex" 
local proc, err = os.spawn{ 
    command = e.."/bin/aprogr", 
    args = { 
     "arg1", 
     "arg2", 
     -- etc 
    }, 
    env = { 
     A = 100, -- I assume it tostrings the value 
     B = "Hi", 
     C = "Test", 
    }, 
    -- you can also specify stdin, stdout, and stderr 
    -- see the proposal page for more info 
} 
if not proc then 
    error("Failed to aprogrinate! "..tostring(err)) 
end 

-- if you want to wait for the process to finish: 
local exitcode = proc:wait() 

lua-ex-pai對POSIX和Windows提供的實現。

你可以找到與LuaForWindows發行版捆綁在一起的這個實現的預編譯二進制文件。

這裏是你的使用情況更加簡潔的版本:

require"ex" 
local file = io.pipe() 
local proc = assert(os.spawn(e.."/bin/aprogr", { 
    env={ A = 100, B = "Hi", C = "Test" }, 
    stdout = file, 
})) 
-- write to file as you wish