0

My C# code:

static string pyExe = "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\python.exe";

var psi = new Process();

string name = "show_ing.py";
string script = "C:\\Users\\micosin\\source\\practiceDotNet\\python\\" + name;
C:\Users\micosin\source\practiceDotNet\python

psi.StartInfo.FileName = pyExe;
psi.StartInfo.Arguments = script;
psi.StartInfo.UseShellExecute = false;
psi.StartInfo.CreateNoWindow = false;
psi.StartInfo.RedirectStandardOutput = true;
psi.StartInfo.RedirectStandardError = true;
psi.StartInfo.StandardErrorEncoding = Encoding.UTF8;
psi.StartInfo.StandardOutputEncoding = Encoding.UTF8;
psi.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
psi.Start();

psi.BeginOutputReadLine();
psi.WaitForExit();

...

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
            Console.WriteLine(e.Data);
}

Python show_ing.py script for creating test output:

# -*- encoding=utf-8 -*-

import sys
import time

print(sys.argv)
while True:
    print('PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP')
    time.sleep(1)

I want get output while the script is running (hence the infinite loop). In testing I only get the output of the script if it exits (no loop).

shox
  • 677
  • 1
  • 5
  • 19
  • Does your callback get called at all? I.e. did you put a breakpoint in p_OutputDataReceived? Maybe your output is going to stderr? See this: https://stackoverflow.com/questions/11994610/c-sharp-get-process-output-while-running – shox May 28 '20 at 16:30
  • yes. i already saw that. the p_OutputDataReceived will called when py going to end. for example the py like as below: print('Doneeeeeeeeeeeeeeeeeeeeeeee') time.sleep(10) print('Doneeeeeeeeeeeeeeeeeeeeeeee') then the callback will be called at seconds later – Evens Mico May 29 '20 at 01:31
  • if i edit my python remove the sleep method and infinite loop . the code is correct – Evens Mico May 29 '20 at 01:37
  • oh, you are using print not println (or whatever the python equivalent is). It's probably not flushing output until it exits. https://stackoverflow.com/questions/230751/how-to-flush-output-of-print-function – shox May 29 '20 at 03:26
  • thank you so much. got it point, i wrong searching keywords of buffer. haha not have concepts about buffer. and Now i know thank you – Evens Mico May 29 '20 at 05:14
  • If you've solved the problem you may want to answer it (in an answer). – shox May 29 '20 at 16:03
  • got it . thank you – Evens Mico Jun 11 '20 at 13:36

1 Answers1

0

The question solution: get the new concepts about buffer.

just to flush buffering to output( use print("Hello world!", flush=True) ). the C# process can be get the output