1

I have a C# code that uses command prompt to call a python script. The script currently takes about 25 seconds to run. When run in command prompt, the python script has several outputs until finally outputting "done". My C# code runs the script, but never closes the command prompt if I use "WaitForExit". So my thought is I need some kind of logic to check to see if "done" has been outputted, but the internet has not been very helpful with methodology.

Here's what I have, it currently only outputs the first line, "Microsoft Windows [Version 6.1.7601]". Obviously, no good.

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();

If there's anyway to close the process after it finishes, or to get all the cmd output I'm all ears.

Any help is appreciated.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Kyle Wright
  • 520
  • 2
  • 9
  • 23
  • Your first suggestion does not seem to output anything. I don't see how this could work without some kind of event structure or loop, when it first hits the "Debug.WriteLine" line, the output I need will not have happened yet. If I use p.BeginOutputReadLine(), what other method do I need to use to capture the output? I can't use p.StandardOutput, apparently that is sync. – Kyle Wright Apr 15 '13 at 19:30
  • this So link may help !!! - http://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results – aked Apr 15 '13 at 19:31
  • It appears that process.BeginOutputReadLine() is all that's needed and that makes everything visible? Doesn't work in my case. – Kyle Wright Apr 15 '13 at 19:48

1 Answers1

1

did you try this event ? Process.OutputDataReceived Event

or Process.ErrorDataReceived Event

here is the code from MSDN

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

... .... ...

private static void SortOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
}
aked
  • 5,625
  • 2
  • 28
  • 33