STEP INTO THE WORLD OF TECHNOLOGICAL INSIGHTS AND INNOVATION

CPython redirected output delayed

Jun 04, 2015

CPython_redirected_output_delayed_a.png

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.

CPython_redirected_b_filename_property.jpg

OutputDataReceived event raises when python script redirects the output. We would create an event handlerOnOutputLineReceived() to handle this .

CPython_redirected_c_output_data_received.jpg

Problem:

Below is the simple python script which uses a loop to print 0 to 9 with 1sec time interval for every loop increment.

CPython_redirected_d_problem.jpg

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:

CPython_redirected_e_result.jpg

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.

CPython_redirected_f_reason.jpg

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

CPython_redirected_g_real_time_output.jpg

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.

Pixentia 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.

 
Contact us today or call 1-855-978-6816 to talk with us about your business needs.
Previously:  Next up: 

Share

News Letter Sign up

Get in touch with us
phone_footer.png  +1 903-306-2430,
              +1 855-978-6816
 
contact-us.jpg