是否有可以执行进程并捕获其stderr
和stdout
流(单独)的Haskell管道?将stdin
传递给流程的能力将是完美的,因为管道也是完美的,但不是必需的(我可以使用文件)。
答案 0 :(得分:4)
以下是来自Haskell学院的文章Data.Conduit.Process的一个例子:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative ((*>))
import Control.Concurrent.Async (Concurrently (..))
import Data.Conduit (await, yield, ($$), (=$))
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Conduit.Process (ClosedStream (..), streamingProcess,
proc, waitForStreamingProcess)
import System.IO (stdin)
main :: IO ()
main = do
putStrLn "Enter lines of data. I'll run ./base64-perl on it."
putStrLn "Enter \"quit\" to exit."
((toProcess, close), fromProcess, fromStderr, cph) <-
streamingProcess (proc "./base64-perl" [])
let input = CB.sourceHandle stdin
$$ CB.lines
=$ inputLoop
=$ toProcess
inputLoop = do
mbs <- await
case mbs of
Nothing -> close
Just "quit" -> close
Just bs -> do
yield bs
inputLoop
output = fromProcess $$ CL.mapM_
(\bs -> putStrLn $ "from process: " ++ show bs)
errout = fromStderr $$ CL.mapM_
(\bs -> putStrLn $ "from stderr: " ++ show bs)
ec <- runConcurrently $
Concurrently input *>
Concurrently output *>
Concurrently errout *>
Concurrently (waitForStreamingProcess cph)
putStrLn $ "Process exit code: " ++ show ec
它基本上是文章中带有处理stderr的线程的例子。
它调用这个perl程序,它向stdout和stderr发送输出:
#!/usr/bin/env perl
use strict;
use warnings;
use MIME::Base64;
$| = 1;
my $timeout = 3;
my $buf = "";
while (1) {
my $rin = '';
vec($rin, fileno(STDIN), 1) = 1;
my ($nfound) = select($rin, undef, undef, $timeout);
if ($nfound) {
my $nread = sysread(STDIN, $buf, 4096, length($buf));
last if $nread <= 0;
print encode_base64($buf);
$buf = "";
} else {
print STDERR "this is from stderr\n";
}
}