c# - 如何在 C# 中捕获 Python 脚本的输出,因为它在运行时打印文本?
问题描述
我有以下 Python 脚本:
import time
for x in range(10):
print(x)
time.sleep(0.05)
我想运行这个脚本并在它运行时捕获它的输出。我使用了以下 C# 代码,但在完全完成循环之前它不会打印任何数字。
private void DoScriptTest()
{
ProcessStartInfo start = new ProcessStartInfo();
string cmd = @"c:\flowers\count.py";
start.FileName = @"C:\Users\pubud\AppData\Local\Programs\Python\Python36\python.exe";
start.Arguments = string.Format("{0}", cmd);
start.UseShellExecute = false;// Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
Process process = new Process();
process.StartInfo = start;
process.EnableRaisingEvents = true;
process.OutputDataReceived += ProcessOutputHandler;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
}
private void ProcessOutputHandler(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
try {
TxtPrompt.Invoke((MethodInvoker)delegate {
TxtPrompt.AppendText(e.Data);
TxtPrompt.Refresh();
});
}
catch
{ }
}
我不确定为什么在脚本运行时没有调用ProcessOutputHandler。我怎么能得到那个输出?(实时来自 Python 脚本的数字)
解决方案
推荐阅读
- javascript - 文档满足条件时未调用 Firestore onRemove
- r - 如何从 apply() 函数输出中获取行名?
- javascript - Javascript - 如何打破循环动画帧?
- python - 编辑现有 XML 文件并通过 Jboss 发送帖子
- javascript - Next/Apollo:如果在 getInitialProps 中运行了相关查询,如何正确更新 apollo 缓存
- c++ - 相互依赖的类中的 C++ 函数指针
- java - Visual Studio 无法正确运行我的代码
- python - TypeError:处理图像时不能将序列乘以“浮点”类型的非整数
- javascript - 用于提取国家名称的正则表达式
- sql - 如何使用我的数据库中的所有表名创建一个表,并为每个表创建表中的列数