我从Starting a process synchronously, and "streaming" the output获取了此代码段:
type ProcessResult = { exitCode : int; stdout : string; stderr : string }
let executeProcess (exe,cmdline) =
let psi = new System.Diagnostics.ProcessStartInfo(exe,cmdline)
psi.UseShellExecute <- false
psi.RedirectStandardOutput <- true
psi.RedirectStandardError <- true
psi.CreateNoWindow <- true
psi.WorkingDirectory <- "C:\\GIT\\ProjectX"
let p = System.Diagnostics.Process.Start(psi)
let output = new System.Text.StringBuilder()
let error = new System.Text.StringBuilder()
p.OutputDataReceived.Add(fun args -> output.Append(args.Data) |> ignore)
p.ErrorDataReceived.Add(fun args -> error.Append(args.Data) |> ignore)
p.BeginErrorReadLine()
p.BeginOutputReadLine()
p.WaitForExit()
{ exitCode = p.ExitCode; stdout = output.ToString(); stderr = error.ToString() }
众所周知,执行结果以类似linux的格式返回一行或多行(行以\ n分隔)
然而,执行以下代码会打印-1,因此\ n已被删除。
let p = executeProcess ("git","branch -vv")
printfn "%d" (p.stdout.IndexOf('\n'))
这个c#中的代码 - 应该等同于上面列出的f# - 效果很好:
private static string[] RetrieveOrphanedBranches(string directory)
{
StringBuilder outputStringBuilder = new StringBuilder();
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.WorkingDirectory = directory;
startInfo.UseShellExecute = false;
startInfo.Arguments = "branch -vv";
startInfo.FileName = "git";
p.StartInfo = startInfo;
p.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
var l = outputStringBuilder.ToString().Split(new char[] { '\n' });
return l;
}
有没有办法防止f#从流程输出中删除换行符?
答案 0 :(得分:4)
&#34;等效&#34;这里用得很自由。
C#代码
p.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
F#代码:
p.OutputDataReceived.Add(fun args -> output.Append(args.Data) |> ignore)
因此在C#中,代码行(带\ n)被添加到输出中。在F#中添加没有\ n。在两者中使用AppendLine。