Making a system call that returns the stdout output as a string

前端 未结 27 1219
误落风尘
误落风尘 2020-11-27 05:13

Perl and PHP do this with backticks. For example,

$output = `ls`;

Returns a directory listing. A similar function, system(\"foo\")

27条回答
  •  醉话见心
    2020-11-27 05:47

    Haskell:

    import Control.Exception
    import System.IO
    import System.Process
    main = bracket (runInteractiveCommand "ls") close $ \(_, hOut, _, _) -> do
        output <- hGetContents hOut
        putStr output
      where close (hIn, hOut, hErr, pid) =
              mapM_ hClose [hIn, hOut, hErr] >> waitForProcess pid
    

    With MissingH installed:

    import System.Cmd.Utils
    main = do
        (pid, output) <- pipeFrom "ls" []
        putStr output
        forceSuccess pid
    

    This is an easy operation in "glue" languages like Perl and Ruby, but Haskell isn't.

提交回复
热议问题