Pet*_*Mmm 6 lua external-process
在我的 Lua 程序中,我必须捕获外部程序的输出。该外部程序需要某些环境变量。所以我这样做:
e = ""
e = e .. "A=100;"
e = e .. "B=Hi;"
e = e .. "C=Test;"
file = io.popen(e .. "/bin/aprogr")
Run Code Online (Sandbox Code Playgroud)
显然,如果环境很大,popen() 的参数可能会超过限制(如果有)。
还有其他方法将环境传递给外部程序吗?
ExtensionProposalos.spawn API中有一个 函数。
您可以按如下方式使用它:
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()
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)