Binding the result of a system command to a variable in Haskell

How to run a system command in Haskell and bind the result (i.e. standard output) to a variable? In pseudo-haskell, I'm looking for something like the following:

import System.Process main = do output <- callCommand "echo hi" putStrLn output -- result: "hi" 

This does not work. Is there something similar?

+5
source share
2 answers

Here is the working code:

 import System.Process main :: IO () main = do let stdin' = "" (errCode, stdout', stderr') <- readProcessWithExitCode "echo" ["hi"] stdin' putStrLn $ "stdout: " ++ stdout' putStrLn $ "stderr: " ++ stderr' putStrLn $ "errCode: " ++ show errCode 

As Karsten notes, you can use readProcess, but I prefer this version because with any serious use, you will soon be very confused about why your command fails silently (if you run both stdout and stderr on the command line, of course, shown).

+6
source

Jamshidh answer extension, if instead of getting stdout and stderr as String you want to get them as ByteString or Text , you can use process-extras .

You can also use my process-streaming package:

 $ import System.Process.Streaming $ execute (piped (shell "echo foo")) (liftA3 (,,) (foldOut intoLazyBytes) (foldErr intoLazyBytes) exitCode) ("foo\n","",ExitSuccess) 

Also for Text :

 $ import System.Process.Streaming.Text $ execute (piped (shell "echo foo")) (liftA3 (,,) (foldOut (transduce1 utf8x intoLazyText)) (foldErr (transduce1 utf8x intoLazyText)) exitCode) ("foo\n","",ExitSuccess) 
+2
source

All Articles