Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Created September 8, 2015 17:38
Show Gist options
  • Save erantapaa/0e62ae87727afd6455b1 to your computer and use it in GitHub Desktop.
Save erantapaa/0e62ae87727afd6455b1 to your computer and use it in GitHub Desktop.
Redirect stdout for an IO action
module Misc
( withOutputTo
) where
import System.IO
import GHC.IO.Handle
import Control.Exception
-- | Run an IO action with stdout redirected to a file.
-- Restores stdout upon completion of the action.
withOutputTo :: FilePath -> IO a -> IO a
withOutputTo path action = do
withFile path WriteMode $ \h -> do
stdout' <- hDuplicate stdout
bracket (hDuplicate stdout)
(\a -> hDuplicateTo a stdout)
(\a -> do hDuplicateTo h stdout
hSetBuffering stdout NoBuffering
action )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment