如何检索从Haskell执行的外部程序的输出? [英] How to retrieve output of external program executed from Haskell?
问题描述
我想从Haskell运行一个外部程序并检索其输出和错误流的内容。在其中一个库中,我找到了这段代码:
runProcess :: FilePath - > [字符串] - > IO(ExitCode,String,String)
runProcess prog args = do
(_,o,e,p)< - runInteractiveProcess编程参数Nothing Nothing
hSetBuffering o NoBuffering
hSetBuffering e NoBuffering
sout < - hGetContents o
serr< - hGetContents e
ecode< - length sout'seq` waitForProcess p
return(ecode,sout,serr)
这是正确的做法吗?在这里有一些我不明白的地方:为什么流设置为 NoBuffering
?为什么长度sout'seq'
?这感觉像是某种黑客。另外,我想将输出和错误流合并为一个,以获得与在命令行上执行 2>& 1
相同的效果。如果可能的话,我想避免使用专用I / O库,并依赖GHC提供的标准软件包。
使用Shelly在Haskell中进行类似shell的编程的模块:
http://hackage.haskell.org/package/shelly-1.4.1/docs/Shelly.html
I want to run an external program from Haskell and retrieve contents of its output and error streams. In one of the libraries I found this code:
runProcess :: FilePath -> [String] -> IO (ExitCode, String, String)
runProcess prog args = do
(_,o,e,p) <- runInteractiveProcess prog args Nothing Nothing
hSetBuffering o NoBuffering
hSetBuffering e NoBuffering
sout <- hGetContents o
serr <- hGetContents e
ecode <- length sout `seq` waitForProcess p
return (ecode, sout, serr)
Is this the right thing to do it? There are some things I don't understand here: why streams are set to NoBuffering
? Why length sout 'seq'
? This feels like some kind of hack. Also, I would like to merge output and error streams into one to get the same effect as if I did 2>&1
on the command line. If possible I want to avoid using dedicated I/O libraries and rely on standard packages provided with GHC.
Use Shelly, a module for shell-like programming in Haskell:
http://hackage.haskell.org/package/shelly-1.4.1/docs/Shelly.html
这篇关于如何检索从Haskell执行的外部程序的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!