Sunday, July 12, 2009

C# calling Python scripts and processing output

Occasionally there would be a situation where the C# needs to call a python script and work with its output. While this might sounds like a piece of cake, it does have its gotcha, that is when
you want to process each line one by one and you happened to have somekind of timing (time.sleep) or some other python codes that works correctly under console but unable to be processed by C#.

Below is how you do it : (read until the end, there is a gotcha)

private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (outLine.Data != null)
Console.Out.WriteLine(outLine.Data.ToString());
}


static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "python.exe";
p.StartInfo.Arguments = "c:\\test\\test.py";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
p.Close();
}



Assuming ur python script is the following (test.py) :

import time
import sys

for x in range(100) :
print x
time.sleep(1)


You will be surprised that you dont get anything. For some reason, time.sleep(1) and possibly
some other python library calls would result in the output not being flushed. The solution
would be to "flush" it :

for x in range(100) :
print x
sys.stdout.flush()



2 comments:

  1. Thank you. I have questions? I want write Console Output String is textBox1.

    ReplyDelete
  2. We are a brazilian software company manufacturer of BPMS and we allow our customers to customize processes using IronPython language. More information www.supravizio.com

    Wallace Oliveira
    www.venki.com.br

    ReplyDelete