Lua 使用环境调用popen
在我的Lua程序中,我必须捕获外部程序的输出。此外部程序需要某些环境变量。所以我这样做:Lua 使用环境调用popen,lua,external-process,Lua,External Process,在我的Lua程序中,我必须捕获外部程序的输出。此外部程序需要某些环境变量。所以我这样做: e = "" e = e .. "A=100;" e = e .. "B=Hi;" e = e .. "C=Test;" file = io.popen(e .. "/bin/aprogr") 显然,如果环境很大,popen()的参数可能会超过限制(如果有) 是否有其他方法将环境传递给外部程序?API中有一个os.spawn函数 您可以按如下方式使用它: require"ex" local proc, e
e = ""
e = e .. "A=100;"
e = e .. "B=Hi;"
e = e .. "C=Test;"
file = io.popen(e .. "/bin/aprogr")
显然,如果环境很大,popen()的参数可能会超过限制(如果有)
是否有其他方法将环境传递给外部程序?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()
提供POSIX和Windows的实现
您可以找到与发行版捆绑在一起的此实现的预编译二进制文件
以下是您的用例的更简明版本:
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