我正在尝试使用
streamly-process
与后台的一些 REPL 进行通信。它可以是 Python 或任何东西,但在这里我尝试运行 GHCi。我想出了以下代码:
import Data.Word
import qualified Streamly.Data.Stream.Prelude as Stream
import qualified Streamly.Data.Fold.Prelude as Fold
import qualified Streamly.System.Process as Process
import qualified Streamly.Console.Stdio as Stdio
import qualified Streamly.Data.Array.Foreign as Array
stringToByteArray :: String -> Array.Array Word8
stringToByteArray = Array.fromList . map (fromIntegral . fromEnum)
-- a version of getLine that does not ignore the newline character.
getNewLn :: IO String
getNewLn = fmap (++ "\n") getLine
main :: IO ()
main = do
Stream.fold (Fold.takeEndBy ( == stringToByteArray "Leaving GHCi.") Stdio.writeChunks) $
Process.pipeChunks "ghci" [] $
fmap stringToByteArray $
Stream.repeatM getNewLn
-- When using Stream.fromList, it works ! To do so, uncomment the following :
-- Stream.fromList ["putStrLn \"This works ! \"\n", " 3 + 4\n"]
当我使用
fromList
时,它按预期工作并返回:
GHCi, version 9.8.2: https://www.haskell.org/ghc/ :? for help
ghci> This works !
ghci> 7
ghci> Leaving GHCi.
但是,当我使用
getNewLn
时,这就是我得到的:
GHCi, version 9.8.2: https://www.haskell.org/ghc/ :? for help
ghci> I'm typing
the return key
several times
but nothing happens ...
我做错了什么?
输入在 pipelineChunks 的输入端得到缓冲。一旦缓冲区中收集到足够数量的输入,它将实际发送到进程(此处为 ghci)。可以通过在 pipelineChunks 实现中应用行缓冲来解决。