0

I have a python program running a c++ program as an executable. the c++ program is printing a few prints with std::cout and after it prints a few printing with printf. when I run the program using regular Popen I see all the printing on the output terminal, but when I use stderr=subprocess.STDOUT,stdout=subprocess.PIPE in the Popen command and after killing program I print the stdout, it's missing the printf output. I tried adding fflush(stdout); in my c++ program and it fixed the issue, but I want to find a way to fix the python script and not the c++ program. How can I fix this issue?

    os.system("taskkill /im program.exe  /F")

    os.chdir(PROGRAM_PATH)

    proc = subprocess.Popen(["program.exe", COM ,FILE],stderr=subprocess.STDOUT,stdout=subprocess.PIPE)

    time.sleep(3)
    
    os.system("taskkill /im program.exe  /F")

    output = proc.stdout.readlines()
    
    for line in output:
        print(line)
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    You have already diagnosed and solved the problem. You are asking how a Python program can force an executable running in a subprocess to flush its output buffer. I don't believe there is any way to do that. Not in Python, not from the shell, not from another C++ program. – BoarGules May 17 '22 at 06:15
  • But it does flush the output buffer when I run it using any other way, including python with- `proc = subprocess.Popen(["program.exe", COM ,FILE])` – Hadass May 17 '22 at 06:41
  • Apparently because the C++ program flushes its buffer differently when writing to a pipe. That is a question for the developers of your C++ compiler. It's really not a Python issue. – BoarGules May 17 '22 at 07:04
  • Bear in mind that when you kill a process, there is no orderly shutdown. When the OS closes a pipe it just disappears. And it may close the pipe before it closes the executable, and so the cut-off is earlier for a pipe. If I was in your shoes I would add a command-line parameter to the C++ program that specifies an orderly shutdown after *n* milliseconds. Then you don't need to kill it and you can be sure of what you're going to get. – BoarGules May 18 '22 at 09:13
  • Thanks for your comment. We don't have a different way in this specific program to shutdown other than killing it, but anyways all the printing is printed in the beginning of running the program and I'm waiting a few seconds before killing it so it should be already printed at that stage for a few seconds... – Hadass May 19 '22 at 11:19
  • If you can change the program to get it to flush the buffer, you can just as easily add a command line parameter to ensure an orderly shutdown. – BoarGules May 19 '22 at 16:26
  • Yes I did do that in the end but I wanted to know if there was a way fix it in the python – Hadass May 22 '22 at 12:46

0 Answers0