2009-08-07 50 views
13

我想这样做相当于:如何用lua构建读写管道?

foo=$(echo "$foo"|someprogram) 
卢阿内

- 也就是说,我有包含了一堆文字的变量,我想通过一个过滤器来运行它(实施在Python中,因为它发生)。

任何提示?

补充:真的想做到这一点,而无需使用临时文件

回答

3

啊哈,一个可能是更好的解决方案:

require('posix') 
require('os') 
require('io') 

function splat_popen(data,cmd) 
    rd,wr = posix.pipe() 
    io.flush() 
    child = posix.fork() 
    if child == 0 then 
     rd:close() 
     wr:write(data) 
     io.flush() 
     os.exit(1) 
    end 
    wr:close() 

    rd2,wr2 = posix.pipe() 
    io.flush() 
    child2 = posix.fork() 
    if child2 == 0 then 
     rd2:close() 
     posix.dup(rd,io.stdin) 
     posix.dup(wr2,io.stdout) 
     posix.exec(cmd) 
     os.exit(2) 
    end 
    wr2:close() 
    rd:close() 

    y = rd2:read("*a") 
    rd2:close() 

    posix.wait(child2) 
    posix.wait(child) 

    return y 
end 

munged=splat_popen("hello, world","/usr/games/rot13") 
print("munged: "..munged.." !") 
+0

为什么我会得到一个关于'要求'的错误? “未知全局变量”要求'“ – 2014-01-29 15:07:35

4

有没有在Lua的标准库,允许这一点。

Here is an in-depth exploration of the difficulties of doing bidirectional communication properly,和所提出的解决方案:

如果可能的话,重定向流(输入或输出)到一个文件的一端。即:

fp = io.popen("foo >/tmp/unique", "w") 
fp:write(anything) 
fp:close() 
fp = io.open("/tmp/unique") 
x = read("*a") 
fp:close() 

您可能感兴趣的this extension这增加了功能的osio命名空间,使有可能一个子进程的双向通信。

+0

是否有某种方式来创建一个LUA子(fork()的或类似)将数据传递到过滤器,像贝壳呢?这将避免僵局... – 2009-08-07 03:31:06

-1

一个不是很好的解决方案,避免了临时文件...

require("io") 
require("posix") 

x="hello\nworld" 

posix.setenv("LUA_X",x) 
i=popen('echo "$LUA_X" | myfilter') 
x=i.read("*a") 
3

只要你的Lua支持io.popen,这个问题很容易。该解决方案是完全按照你所概述的,除了没有$(...)你需要这样一个功能:

function os.capture(cmd, raw) 
    local f = assert(io.popen(cmd, 'r')) 
    local s = assert(f:read('*a')) 
    f:close() 
    if raw then return s end 
    s = string.gsub(s, '^%s+', '') 
    s = string.gsub(s, '%s+$', '') 
    s = string.gsub(s, '[\n\r]+', ' ') 
    return s 
end 

然后可以调用

local foo = ... 
local cmd = ("echo $foo | someprogram"):gsub('$foo', foo) 
foo = os.capture(cmd) 

我做的东西像这一切的时候。下面是形成命令的相关有用的功能:

local quote_me = '[^%w%+%-%=%@%_%/]' -- complement (needn't quote) 
local strfind = string.find 

function os.quote(s) 
    if strfind(s, quote_me) or s == '' then 
    return "'" .. string.gsub(s, "'", [['"'"']]) .. "'" 
    else 
    return s 
    end 
end 
+0

这不捕获stderr。有没有办法捕捉它呢? – 2011-02-27 17:25:17

+0

@Vilas,如果你不介意混合stderr和stdout,只需在命令行中添加'2>&1'即可。或者查看Debian脚本'annotate-output'。 – 2011-02-28 03:28:45

+0

对这种方法非常小心---最终会在命令行中传递'foo'的全部内容,并且不能保证命令行有多大。您的数据最终也会公开显示,因为它会显示在流程列表中。 – 2014-09-21 16:59:36

0

这里是我解决了这个问题,它需要lua posix

  p = require 'posix' 
      local r,w = p.pipe() 
      local r1,w1 = p.pipe() 
      local cpid = p.fork() 
      if cpid == 0 then -- child reads from pipe          
      w:close() 
      r1:close() 
      p.dup(r, io.stdin) 
      p.dup(w1 ,io.stdout) 
      p.exec('./myProgram') 
      r:close() 
      w1:close() 
      p._exit(0) 
      else -- parent writes to pipe             
      IN = r1 
      OUT = w 
      end 

myProgram执行,you'l读取和正常IO写,这部分代码后,你只需要读/写上INOUT与儿童节目comunicate。

2

我偶然发现了这篇文章,同时尝试做同样的事情,从来没有找到一个好的解决方案,请参阅下面的代码,以解决我的问题。此实现允许用户访问stdin,stdout,stderr并获取返回状态码。一个简单的包装被称为简单的管道调用。

require("posix") 

-- 
-- Simple popen3() implementation 
-- 
function popen3(path, ...) 
    local r1, w1 = posix.pipe() 
    local r2, w2 = posix.pipe() 
    local r3, w3 = posix.pipe() 

    assert((w1 ~= nil or r2 ~= nil or r3 ~= nil), "pipe() failed") 

    local pid, err = posix.fork() 
    assert(pid ~= nil, "fork() failed") 
    if pid == 0 then 
     posix.close(w1) 
     posix.close(r2) 
     posix.dup2(r1, posix.fileno(io.stdin)) 
     posix.dup2(w2, posix.fileno(io.stdout)) 
     posix.dup2(w3, posix.fileno(io.stderr)) 
     posix.close(r1) 
     posix.close(w2) 
     posix.close(w3) 

     local ret, err = posix.execp(path, unpack({...})) 
     assert(ret ~= nil, "execp() failed") 

     posix._exit(1) 
     return 
    end 

    posix.close(r1) 
    posix.close(w2) 
    posix.close(w3) 

    return pid, w1, r2, r3 
end 

-- 
-- Pipe input into cmd + optional arguments and wait for completion 
-- and then return status code, stdout and stderr from cmd. 
-- 
function pipe_simple(input, cmd, ...) 
    -- 
    -- Launch child process 
    -- 
    local pid, w, r, e = popen3(cmd, unpack({...})) 
    assert(pid ~= nil, "filter() unable to popen3()") 

    -- 
    -- Write to popen3's stdin, important to close it as some (most?) proccess 
    -- block until the stdin pipe is closed 
    -- 
    posix.write(w, input) 
    posix.close(w) 

    local bufsize = 4096 
    -- 
    -- Read popen3's stdout via Posix file handle 
    -- 
    local stdout = {} 
    local i = 1 
    while true do 
     buf = posix.read(r, bufsize) 
     if buf == nil or #buf == 0 then break end 
     stdout[i] = buf 
     i = i + 1 
    end 

    -- 
    -- Read popen3's stderr via Posix file handle 
    -- 
    local stderr = {} 
    local i = 1 
    while true do 
     buf = posix.read(e, bufsize) 
     if buf == nil or #buf == 0 then break end 
     stderr[i] = buf 
     i = i + 1 
    end 

    -- 
    -- Clean-up child (no zombies) and get return status 
    -- 
    local wait_pid, wait_cause, wait_status = posix.wait(pid) 

    return wait_status, table.concat(stdout), table.concat(stderr) 
end 

-- 
-- Example usage 
-- 
local my_in = io.stdin:read("*all") 
--local my_cmd = "wc" 
--local my_args = {"-l"} 
local my_cmd = "spamc" 
local my_args = {} -- no arguments 
local my_status, my_out, my_err = pipe_simple(my_in, my_cmd, unpack(my_args)) 

-- Obviously not interleaved as they would have been if printed in realtime 
io.stdout:write(my_out) 
io.stderr:write(my_err) 

os.exit(my_status) 
+0

这是相当不错,但你确定这是作为提出?文件描述符编号是逐个(应该是0,1和2),并且fork和execp错误的测试看起来与我相反。 – jpc 2016-02-27 20:44:18

+0

大部分作品都是为我写的,不得不添加'local posix = require(“posix”)'。 – robm 2016-09-24 09:40:33

+0

我必须在循环之后添加'posix.close(r)'和'posix.close(e)'以将它们排入ps.pipe_simple()中。否则,在Linux上进行500次调用后会出现“打开的文件过多”。 – robm 2017-04-05 07:32:37

0

这很容易,没有必要的扩展(与卢阿5.3测试)。

#!/usr/bin/lua 
-- use always locals 
local stdin = io.stdin:lines() 
local stdout = io.write 

for line in stdin do 
    stdout (line) 
end 

另存为inout.luachmod +x /tmp/inout.lua

20:30 $ foo=$(echo "bla"| /tmp/inout.lua) 
20:30 $ echo $foo 
bla