我正在尝试编写一段C#代码,它使用了一小部分Python代码,然后尝试在我的应用程序中输出Python代码。目标是拥有一个Python RSS,它可以生成少量数据并输出。
我希望C#代码执行此代码并捕获所有生成的行,但它只捕获第一行。
以下是python输出的示例:
Business Superjumbo jet future secured by Emirates order. A big order from Emirates airline saves the A380 after Airbus threatened to stop making the plane.
Business Banks create funds for firms hit by Carillion collapse. Lloyds and RBS will provide cash for struggling small firms as Nationwide takes on Carillion staff.
Politics Theresa May meets Macron with pledge of extra £44m for border. The UK pledges an extra £44m for channel border security ahead of the Anglo-French summit.
这是生成数据的简短摘录,但C#(结果变量)仅捕获第一行,有时两行。
我做错了什么或无法使用此方法获取所有打印件?
C#代码
start.Arguments = "../test/smallWebCrawl.py";
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)
try
{
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
//Console.WriteLine(stderr);
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
Console.WriteLine(result);
}
}
}
catch (Exception)
{
Console.WriteLine("Error. Wrong python path");
}
答案 0 :(得分:0)
所以我设法找到了一个替代解决方案,它有效并且我决定使用它,虽然它不是最好的,但我热衷于保留代码的整体结构,就像它一样。
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd();
process.WaitForExit();
string result = reader.ReadToEnd();
string text = File.ReadAllText(start.WorkingDirectory + "\\t.txt");
基本上,我等待退出我的Python脚本以确保所有数据都已写入文件,然后读取整个生成的文本文件,以后可以删除。