Introduction :
Python scripts can be run using CPython in C#. Unlike Command prompt, when we run the scripts in C# using CPython we encountered with a problem to get the real time output. This blog depicts the reason behind the problem and how to figure out this with a simple solution.
How to run python scripts in C# using CPython:
In C#, we can run the python script using process.Start () method. And the runtime environment is created bypython.exe. This is set to Filename property of a Process class in .Net framework.
OutputDataReceived event raises when python script redirects the output. We would create an event handlerOnOutputLineReceived() to handle this .
Problem:
Below is the simple python script which uses a loop to print 0 to 9 with 1sec time interval for every loop increment.
When the debugger executes the print statements, the real time output needs to be displayed on the screen. But unfortunately the output is at once displayed after the completion of whole execution of the script .
Result:
Reason and Solution:
We further investigated into the problem and got to know that, Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal.
As we kept sys.stdout.flush(), after every print statement the output gets redirected eventually.
Result:
Below screen grab shows the real time output retrieved from the script
Conclusion:
Now we are able to get the real time output similar to command prompt with the help of this flushing concept. Another way to execute the python scripts in C# is by using embedded Iron Python where there is no question of flushing the memory every time.
Phenomecloud is an enthusiastic family of individuals, fervent to make lives simpler through effective use of technology. Our mission is to implement solutions that drives business results. Know more insights from our thoughts and experience.
Leave a Comment