Answer the question
In order to leave comments, you need to log in
C# Capturing the output of a running console application
In "real time" I'm trying to get the output of a console application launched from my program.
I tried OutputDataReceived, to no avail - the event occurs only after the console window is closed.
How to be? o_O Rummaged half of Google already ...
Code: http://pastie.org/1918574
correction: on a test program that just reads lines into the console - everything is ok. on a python script compiled into an exe, it is empty, only after the console is closed, the event fires ... maybe this is the case, although what difference it makes is not clear.
Answer the question
In order to leave comments, you need to log in
I am very remotely familiar with Python, but based on the symptoms of the problem, I believe that Python is just buffering the output. And you can try to disable this buffering:
Here is a discussion on the topic on stackoverflow:
Python output buffering
Also look at the additional settings for launching a console process from C#:
How to parse command line output from c# ??
Everything is done by redirecting the output stream to String
public class CommandHelpers
{
public CommandHelpers()
{
Invisible = true; // При переадресации утилита должна быть скрыта
}
public bool Invisible { get; set; }
private Process CreateProcess(string commandName, IEnumerable<string> paramsList, bool output = false)
{
string paramString = paramsList.Aggregate<string, string>(null,
(current, param) => current + " " + param);
return new Process
{
StartInfo =
{
FileName = commandName, // полный путь до инстансыруемого приложения
Arguments = paramString, // сюда передаются аргументы командной строки
UseShellExecute = output ? !output : !Invisible, // Параметр отвечает за фоновое выполнение
RedirectStandardOutput = output // Параметр отвечает за переадресацию
}
};
}
/// <summary>
/// Returns result of command execution
/// </summary>
/// <param name="commandName">Command name only</param>
/// <param name="paramsList">Params and keys for command</param>
/// <returns></returns>
public string GetResult(string commandName, IEnumerable<string> paramsList)
{
var bufer = new StringBuilder();
using (var proc = CreateProcess(commandName, paramsList, true))
{
proc.Start(); // инстансыруемся
while (!proc.StandardOutput.EndOfStream)
{
bufer.AppendLine(proc.StandardOutput.ReadLine()); // пишем в буфер
}
}
return bufer.ToString();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question