Skip to content

Instantly share code, notes, and snippets.

@fujimura
Created October 27, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujimura/58ff6782e881f0d49455 to your computer and use it in GitHub Desktop.
Save fujimura/58ff6782e881f0d49455 to your computer and use it in GitHub Desktop.
Run program with mocked stdin
import Control.Exception
import GHC.IO.Handle
import System.IO
import System.IO.Temp
main :: IO ()
main = do
runWithStdin "Ornette Coleman Trio\nAt the Golden Circle Stockholm" $ do
getLine >>= putStrLn
getLine >>= putStrLn
runWithStdin "Albert Ayler\nSpiritual Unity" $ do
getLine >>= putStrLn
getLine >>= putStrLn
runWithStdin :: String -> IO () -> IO ()
runWithStdin input action = do
withSystemTempFile "runWithInput" $ \path handle -> do
hPutStrLn handle input
hClose handle
handle' <- openFile path ReadMode
stdin' <- hDuplicate stdin
hDuplicateTo handle' stdin
finally action $ do
hDuplicateTo stdin' stdin
hClose handle'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment