Call popen with environment

1.3k views Asked by At

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 ?

2

There are 2 answers

0
Deco On

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
0
rlranft On

For "pure" Lua I just write a batch file with the necessary instructions in it to set up env and call the command, then io.popen(mybatchfile).