Call popen with environment

这一生的挚爱 提交于 2019-12-23 20:10:53

问题


In my Lua program i have to catch output from an external program. This external program needs certain environment variables. So i do this:

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

Obviously the argument for popen() may pass the limit (if any) if the environment is large.

Is there any other way to pass the environment to the external program ?


回答1:


There is an os.spawn function in the ExtensionProposal API.

You can use it as follows:

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 provides implementations for POSIX and Windows.

You can find precompiled binaries of this implementation bundled with the LuaForWindows distribution.

Here is a more concise version of your use case:

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


来源:https://stackoverflow.com/questions/8838038/call-popen-with-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!