lua - 使用环境调用 popen

标签 lua external-process

在我的 Lua 程序中,我必须捕获来自外部程序的输出。这个外部程序需要某些环境变量。所以我这样做:

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

显然,如果环境很大,popen() 的参数可能会超过限制(如果有的话)。

有没有其他方法可以将环境传递给外部程序?

最佳答案

有一个os.spawn ExtensionProposal 中的函数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()

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

关于lua - 使用环境调用 popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8838038/

相关文章:

variables - 如何使用字符串和连接访问变量名

lua - 比较Lua中的两个数字时计算位数的差异

lua - Neovim + Lua : how to use different mappings depending on file type?

java - 从 java jar 运行 R 脚本

c++ - 确保在外部进程中创建文件时刷新文件 (Win32)

python - 在Python中执行和监控外部程序的多个实例

lua - Corona SDK - 从 eventListener 调用实例方法或类方法

Lua = 操作符作为打印

browser - 在 Firefox 或 chrome 中启动外部程序

python - 如何在python中调用外部程序并检索输出和返回代码?