11

I want to run an external program from Haskell and retrieve the 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 way 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.

6
  • I'm not sure it's possible to get the same effect as if you do 2>&1 in the shell. Is there any particular reason you would want that?
    – kqr
    Jan 30, 2014 at 19:45
  • 2
    I'd say the reason for seq is to force consuming the complete output of the program. Otherwise (since the strings are lazy) a deadlock could happen: the sub-process would be waiting on writing its output and the master process waiting for the process to finish. But it seems there could be the same problem with serr, I'd be worried that if the program wrote a lot of output to its stderr, the above code could hang as well. Doing this right probably won't be very simple, so I'd perhaps rather look for some stable IO library that solves the problem already.
    – Petr
    Jan 30, 2014 at 19:49
  • Also do you need the program to be multi-platform, or are you targeting a specific platform?
    – Petr
    Jan 30, 2014 at 19:50
  • 1
    The process library has the function readProcessWithExitCode that returns both stdout and stderr as strings. If the process writes a lot of output, if you want to have access to the output while the program is running, or if you want stdout and stderr to be interleaved, this won't be enough though.
    – danidiaz
    Jan 30, 2014 at 20:57
  • 4
    If you use runProcess and pass in the same handle for stdout and stderr (instead of Nothing), it should work like 2>&1.
    – hammar
    Jan 30, 2014 at 21:15

3 Answers 3

4

Use Shelly, a module for shell-like programming in Haskell:

http://hackage.haskell.org/package/shelly-1.4.1/docs/Shelly.html

4

This example program uses the process, async, pipes, and pipes-bytestring packages to execute an external command and write stdout and stderr to separate files while the command runs:

import Control.Applicative
import Control.Monad
import Control.Concurrent
import Control.Concurrent.Async
import Control.Exception
import Pipes
import qualified Pipes.ByteString as P
import Pipes.Concurrent
import System.Process
import System.IO

writeToFile :: Handle -> FilePath -> IO ()
writeToFile handle path = 
    finally (withFile path WriteMode $ \hOut ->
                runEffect $ P.fromHandle handle >-> P.toHandle hOut)
            (hClose handle) 

main :: IO ()
main = do
   (_,mOut,mErr,procHandle) <- createProcess $ 
        (proc "foo" ["--help"]) { std_out = CreatePipe
                                , std_err = CreatePipe 
                                }
   let (hOut,hErr) = maybe (error "bogus handles") 
                           id
                           ((,) <$> mOut <*> mErr)
   a1 <- async $ writeToFile hOut "stdout.txt" 
   a2 <- async $ writeToFile hErr "stderr.txt" 
   waitBoth a1 a2
   return ()

And this is a variation that writes stdout and stderr interleaved to the same file:

writeToMailbox :: Handle -> Output ByteString -> IO ()
writeToMailbox handle oMailbox = 
     finally (runEffect $ P.fromHandle handle >-> toOutput oMailbox)
             (hClose handle) 

writeToFile :: Input ByteString -> FilePath -> IO ()
writeToFile iMailbox path = 
    withFile path WriteMode $ \hOut ->
         runEffect $ fromInput iMailbox >-> P.toHandle hOut

main :: IO ()
main = do
   (_,mOut,mErr,procHandle) <- createProcess $ 
        (proc "foo" ["--help"]) { std_out = CreatePipe
                                , std_err = CreatePipe 
                                }
   let (hOut,hErr) = maybe (error "bogus handles") 
                           id
                           ((,) <$> mOut <*> mErr)
   (mailBoxOut,mailBoxIn,seal) <- spawn' Unbounded
   a1 <- async $ writeToMailbox hOut mailBoxOut 
   a2 <- async $ writeToMailbox hErr mailBoxOut 
   a3 <- async $ waitBoth a1 a2 >> atomically seal 
   writeToFile mailBoxIn "combined.txt" 
   wait a3
   return ()

It uses pipes-concurrent. The threads that drain each handle write to the same mailbox. The mailbox is read by the main thread, which writes the output file while the command runs.

3

I find readProcessWithExitCode for this purpose very succinct.

Here's an example using only functions from GHC's standard libraries. The program lists the files of your home directory sorted by size, printing the process' exit code as well as the contents of the standard out and standard error streams:

import           System.Directory               ( getHomeDirectory )
import           System.Process                 ( readProcessWithExitCode )
import           System.Exit                    ( ExitCode )
import           Data.List.NonEmpty

callCmd :: NonEmpty String -> IO (ExitCode, String, String)
callCmd (cmd :| args) = readProcessWithExitCode cmd args stdIn
  where stdIn = ""

main = do
  home                       <- getHomeDirectory
  (exitCode, stdOut, stdErr) <-
    callCmd $ "ls" :| [home, "--almost-all", "-l", "-S"]
  putStrLn
    $  "Exit code: "
    ++ show exitCode
    ++ "\nOut: "
    ++ stdOut
    ++ "\nErr: "
    ++ stdErr
2
  • Is the :| an operator in callCmd (cmd :| args) = readProcessWithExitCode cmd args stdIn where stdIn = ""? If so, which one? To my knowledge, : is the list append operator, but what about the |? And it is also used by the caller in callCmd $ "ls" :| [home, "--almost-all", "-l", "-S"]. So it is creating a list of arguments, but why and when is it needed (is this shorthand like callCmd $? Maybe it would help to know how to read this (cmd :| args) notation in Plain English. Nicely done by the way. Mar 24 at 11:35
  • 1
    :| is the constructor for creating a non-empty list. In callCmd (cmd :| args) it's used as a deconstructor to get the first element (cmd) of the non-empty list and the rest of the list, args. Mar 24 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.