Read Windows Command Prompt STDOUT

梦想与她 提交于 2019-12-25 08:20:13

问题


I have a command line application that runs on a windows server. The command prompt remains open when the program is running, and log messages are output to the command prompt window as the program functions.

My need is to read the messages that appear on the command prompt as the program runs, and then run particular commands if a specific set of words appear in the messages.

What's the easiest way to do this on a windows machine? (without modifying the app)


回答1:


Reading those two posts will give you the solution:

  1. ProcessStartInfo
  2. Capturing console output.

The idea is to to run your app (not modifying it) from your new app (written in C#) and redirect its input-output here, reading and writing as you please.

An example could be:

Process proc;
void RunApp()
{
    proc = new Process();
    proc.StartInfo.FileName = "your_app.exe";
    proc.StartInfo.Arguments = ""; // If needed
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardInput = true;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.OutputDataReceived += new DataReceivedEventHandler(InterProcOutputHandler);
    proc.Start();
    proc.WaitForExit();
}
void InterProcOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    // Read data here
    ...
    // Send command if necessary
    proc.StandardInput.WriteLine("your_command");
}


来源:https://stackoverflow.com/questions/8892445/read-windows-command-prompt-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!