haskellio-redirectionhaskell-stackhint

hint runStmt no output when redirected


Following this link and trying to stack run this module:

module Main where

import Language.Haskell.Interpreter

main :: IO ()
main = do
  _ <- runInterpreter
     $ setImports ["Prelude"]
    >> runStmt "x <- pure 42"
    >> runStmt "print x"
  return ()

there is no output when redirected from the command line:

user@localhost ~/hs-project $ stack run > 42.txt

I can only guess that - unlike in an answer from the mentioned post - the output of hint goes through pipes, because "print" runs inside the interpreter, doesn't come from the module.

This is the result of ls -l /proc/<pid>/fd.

lrwx------ 1 user user 64 31 mei 20:50 0 -> /dev/pts/4
lrwx------ 1 user user 64 31 mei 20:50 1 -> /dev/pts/4
lrwx------ 1 user user 64 31 mei 20:50 2 -> /dev/pts/4
lrwx------ 1 user user 64 31 mei 20:50 3 -> 'anon_inode:[timerfd]'
lr-x------ 1 user user 64 31 mei 20:50 4 -> 'pipe:[2705380]'
lr-x------ 1 user user 64 31 mei 20:50 6 -> 'pipe:[2705381]'

Solution

  • Try having the interpreter flush its output before exiting:

    _ <- runInterpreter
       $ setImports ["Prelude", "System.IO"]
       >> runStmt "x <- pure 42"
       >> runStmt "print x"
       >> runStmt "hFlush stdout"
    

    or turn off buffering before generating output:

    _ <- runInterpreter
       $ setImports ["Prelude", "System.IO"]
       >> runStmt "hSetBuffering stdout NoBuffering"
       >> runStmt "x <- pure 42"
       >> runStmt "print x"
    

    Both approaches seemed to work for me.