用环境打电话给popen

时间:2012-01-12 15:54:39

标签: lua external-process

在我的Lua程序中,我必须从外部程序中捕获输出。此外部程序需要某些环境变量。所以我这样做:

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

显然,如果环境很大,popen()的参数可以通过限制(如果有的话)。

有没有其他方法可以将环境传递给外部程序?

1 个答案:

答案 0 :(得分: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