1

我有一个使用命令提示符调用 python 脚本的 C# 代码。该脚本当前运行大约需要 25 秒。在命令提示符下运行时,python 脚本有几个输出,直到最终输出“完成”。我的 C# 代码运行脚本,但如果我使用“WaitForExit”,则永远不会关闭命令提示符。所以我的想法是我需要某种逻辑来检查是否已输出“完成”,但互联网对方法论的帮助并不大。

这就是我所拥有的,它目前只输出第一行“Microsoft Windows [Version 6.1.7601]”。显然,不好。

var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = @"C:\Optimization";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;


p.Start();


p.StandardInput.WriteLine(@"ipy spot_for_labview.py");

    StreamReader mySR = p.StandardOutput;
    string mystr = mySR.ReadLine();
    Debug.WriteLine(mystr);



p.WaitForExit(25000);  //25000 is a placeholder until better method found.

p.Close();

如果无论如何要在完成后关闭该过程,或者要获得所有 cmd 输出,我都会听。

任何帮助表示赞赏。

4

1 回答 1

1

你试过这个活动吗?Process.OutputDataReceived事件

Process.ErrorDataReceived 事件

这是来自 MSDN 的代码

    Process sortProcess;
    sortProcess = new Process();
    sortProcess.StartInfo.FileName = "Sort.exe";
    sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);

………………

private static void SortOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
}
于 2013-04-15T19:13:14.060 回答