问题
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