Search code examples
haskellexecutablepipesubprocesspopen

Closest equivalent to subprocess.communicate in Haskell


I want to do a popen() / python's subprocess.communicate from Haskell - start a program, give it stdin, and get its stdout/stderr. What's the most direct / Haskellish way to do this?


Solution

  • Pick either MissingH's System.Cmd.Utils and the standard library's System.Process. They're easy to use, with both high-level convenience functions (which you simply throw strings at and get strings back, possibly lazily) and low-level plumbing functions (which actually give you handles, like most popen functions in other languages/frameworks).

    import System.Process
    
    main = do
        let cmd = "mail"
            args = ["root@localhost", "-s", "does this act like popen?"]
            input = ["Hello, world!"]
        (rc, out, err) <- readProcessWithExitCode cmd args input
        putStrLn $ "mail exited: " ++ show rc
        mapM_ putStrLn $ map ("out: " ++) $ lines out
        mapM_ putStrLn $ map ("err: " ++) $ lines err