Skip to content

Instantly share code, notes, and snippets.

@rmunn
Created February 2, 2019 17:21
Show Gist options
  • Save rmunn/11dc4427be513f4ce6c6fb1408ddb62d to your computer and use it in GitHub Desktop.
Save rmunn/11dc4427be513f4ce6c6fb1408ddb62d to your computer and use it in GitHub Desktop.
How I would prefer to write https://stackoverflow.com/a/54494511/2314532
let RunProcess (startInfo : ProcessStartInfo) =
let bufferOutput = new StringBuilder()
let bufferError = new StringBuilder()
let dataHandler handler = DataReceivedEventHandler(fun sender args -> try handler args.Data with _ -> ())
let append (sb: StringBuilder) txt = sb.Append(txt + "\n") |> ignore
let consume (sb: StringBuilder) = sb.ToString() |>! (fun _ -> sb.Clear() |> ignore)
let outputHandler = append bufferOutput |> dataHandler
let errorHandler = append bufferError |> dataHandler
startInfo.RedirectStandardInput <- true
startInfo.RedirectStandardOutput <- true
startInfo.RedirectStandardError <- true
startInfo.UseShellExecute <- false
let proc = new Process(StartInfo = startInfo,
EnableRaisingEvents = true)
outputHandler |> proc.OutputDataReceived.AddHandler
errorHandler |> proc.ErrorDataReceived .AddHandler
let r = proc.Start()
proc.BeginOutputReadLine()
proc.BeginErrorReadLine()
proc.WaitForExit()
let output = (consume bufferOutput).Trim()
let error = (consume bufferError ).Trim()
((if proc.HasExited then proc.ExitCode else -99999), output, error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment