我正在制作一个应用程序,前端使用 Visual C#,后端使用 Python 执行脚本。我想将 Visual c# 表单中的一个值作为参数传递给 Python 脚本。 Python 脚本应处理该值并将处理后的值返回给 Visual c#。该值应以 Visual C# 形式显示。
首先,我编写了一段脏代码,在加载表单时执行 python 脚本并将值存储在文本文件中。 Python 脚本将使用该值进行计算。但我无法将值返回给 c#。
我为第一个逻辑编写的代码是:
Process process = new Process();
process.StartInfo.CreateNoWindow = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.FileName = @"C:\c#\Work\RulesValidator\RulesValidator\Asset_Id.py";
try
{
process.Start();
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
asset_id.Text = System.IO.File.ReadAllText(@"C:\c#\Work\RulesValidator\RulesValidator\Asset_Id.txt");
最佳答案
问题是您启动子 Python 脚本并立即尝试读取顺序文件而不等待子脚本结束。
你应该尝试:
Process process = new Process();
process.StartInfo.CreateNoWindow = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.FileName = @"C:\c#\Work\RulesValidator\RulesValidator\Asset_Id.py";
try
{
process.Start();
process.WaitForExit(); // Now child should have done its job and closed file
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
asset_id.Text = System.IO.File.ReadAllText(@"C:\c#\Work\RulesValidator\RulesValidator\Asset_Id.txt");
但是你应该研究一下 e-nouri 提出的方法。唯一需要注意的一点是:要使用 StandardOutput,必须将 ProcessStartInfo.UseShellExecute 设置为 false。在 Python 部分,您只需将结果写入 stdout,所有其他输出都会写入 stderr。
可能是(改编自 MSDN 上的 this page):
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @"C:\c#\Path\To\python.exe";
p.StartInfo.Arguments = @"C:\c#\Work\RulesValidator\RulesValidator\Asset_Id.py";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
注意:我没有 C# 开发环境,并且上面的内容未经测试,即使我诚实地认为它应该离你想要的不远
关于c# - 将 C# 中的值作为参数传递给 python,并从 Python 接收处理后的值并显示在 C# 表单上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700094/