Created
September 8, 2015 17:38
-
-
Save erantapaa/0e62ae87727afd6455b1 to your computer and use it in GitHub Desktop.
Redirect stdout for an IO action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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