将一个值作为C#中的参数传递给python,并从python接收处理后的值,并在C#表单上显示
我正在制作一个应用程序,前端使用visual c#,后端使用Python执行脚本。我想将Visual c#form中的一个值作为参数传递给Python脚本。Python脚本应处理该值,并将处理后的值返回给Visual c#。该值应以visual c#形式显示 首先,我编写了一个脏代码,其中加载表单时执行python脚本,并将值存储在文本文件中。Python脚本将使用该值进行计算。但我无法将值返回到c 我为第一个逻辑编写的代码是:将一个值作为C#中的参数传递给python,并从python接收处理后的值,并在C#表单上显示,c#,python,C#,Python,我正在制作一个应用程序,前端使用visual c#,后端使用Python执行脚本。我想将Visual c#form中的一个值作为参数传递给Python脚本。Python脚本应处理该值,并将处理后的值返回给Visual c#。该值应以visual c#形式显示 首先,我编写了一个脏代码,其中加载表单时执行python脚本,并将值存储在文本文件中。Python脚本将使用该值进行计算。但我无法将值返回到c 我为第一个逻辑编写的代码是: Process process = new Process();
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");
您可以生成一个进程并捕获它的标准输出,这里有一个SO问题:。 在python程序/脚本中,您可以使用打印到标准输出的打印,然后从C#代码中捕获它。根据要交换的数据的复杂性,可以使用纯文本、json等
干杯,问题是启动子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上的内容进行改编):
注意:我没有C#开发环境,而且上面的环境没有经过测试,即使我真的认为它应该离你想要的不远你有没有研究过为这种类型的东西定制的IronPython@丹尼尔。。我看了铁蟒的笔记,但没得到多少。我现在将检查该选项。谢谢
// 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();