0

I have made a C# app which calls a python script. C# app uses Process object to call python script. I also have redirected the sub-process standard output so I can process the output from python script.

But the problem is: The output(via print function) from python will always arrive at once when the script terminates. I want the output to arrive in real time while script running.

I can say I have tried almost all of method can get from google, like add flush of sys.out, redirect sysout in python, C# event driven message receiving or just using while to wait message etc,.

How to flush output of print function?

PyInstaller packaged application works fine in Console mode, crashes in Window mode

I am very wondering that like PyCharm or other python IDE, they run python script inside, but they can print the output one by one without hacking original python script, how they do that?

The python version is 2.7. Hope to have advise.

Thank you!

Li JianMing
  • 47
  • 2
  • 6

1 Answers1

0

I just use very stupid but working method to resolve it:

using thread to periodically flush the sys.out, the code piece is like this:

import sys
import os
import threading
import time


run_thread = False


def flush_print():
    while run_thread:
       # print 'something'
        sys.stdout.flush()
        time.sleep(1)

in main function:

if __name__ == '__main__':
    thread = threading.Thread(target=flush_print)
    run_thread = True
    thread.start()

    # my big functions with some prints, the function will block until completed

    run_thread = False
    thread.join()

Apparently this is ugly, but I have no better method to make work done .

Li JianMing
  • 47
  • 2
  • 6