用环境调用popen [英] Call popen with environment

查看:94
本文介绍了用环境调用popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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的实现. /p>

您可以找到与 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

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 ?

解决方案

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

这篇关于用环境调用popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆