从控制台应用程序异步获取标准输出,而无需等待控制台退出 [英] Getting stdout from console app asyncronously without waiting for console to exit

查看:170
本文介绍了从控制台应用程序异步获取标准输出,而无需等待控制台退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序产生了一个小型的长时间运行的控制台应用程序,无法获得一些控制台标准输出的问题.

I have an issue with getting some console standard output from a small long running console app spawned by my application.

我的应用程序启动了控制台应用程序,并且控制台应用程序将在我的应用程序生命周期内(或直到被明确终止)一直保持监听端口状态.

My app starts the console app and the console app will stay alive listening on a port for the duration of my applications lifetime (or until explicitly killed).

启动控制台应用程序时,它将输出正在监听的端口号,我需要异步获取该端口号,并在应用程序中的其他位置使用它.问题是,我的事件处理程序从未获取输出数据.我敢肯定,我一定会忘记一些琐碎的事情.

When the console app starts, it outputs a port number that it is listening on, I need to asyncronously grab that port number and use it elsewhere in the app. Problem is, my event handler to get the output data is never called. I am sure there must be something trivial I am forgetting to do.

  ProcessStartInfo si = new ProcessStartInfo();
  si.FileName = theFileName;
  si.Arguments = theargs;
  si.UseShellExecute = false;
  si.RedirectStandardOutput = true;
  si.CreateNoWindow = true;
  _process = Process.Start(si);
  _process.OutputDataReceived += (sender, args) =>
    {
      //Parse the args.Data string for the port number.
    };
  _process.BeginOutputReadLine(); // My handler never gets called.
  // I don't want to call _process.WaitForExit() here as this is a long running process.

推荐答案

在我的特殊情况下,问题是由控制台应用程序未刷新标准输出引起的.

Ok in my particular case the issue was caused by the console app not flushing stdout.

控制台应用程序是用python编写的(然后由py2exe在Windows中运行),这需要...

The console app was written in python (then made runnable in windows by py2exe), it required...

sys.stdout.flush()

在应用退出之前获得任何输出之前被调用.

To be called before we could get any output prior to app exit.

这篇关于从控制台应用程序异步获取标准输出,而无需等待控制台退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆