Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Created June 1, 2016 07:01
Show Gist options
  • Save erantapaa/dfe01144d79cbb6701b50f37e945f988 to your computer and use it in GitHub Desktop.
Save erantapaa/dfe01144d79cbb6701b50f37e945f988 to your computer and use it in GitHub Desktop.
withOutputTo
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