2009-08-07 144 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