c# - 将 C# 中的值作为参数传递给 python,并从 Python 接收处理后的值并显示在 C# 表单上

标签 c# python

我正在制作一个应用程序,前端使用 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/

相关文章:

python - 对于多平台 GPGPU 计算,是否有 OpenCL+PyOpenCL 的替代方案?

c# - 多线程计算从多个文件加载数据。如何在 C# 中使用和同步 StreamReader?

c# - 模型 View 演示器 : Why is model static?

c# - 如何从 Azure 函数中获取多个 blob?

Python int 太大,无法转换为 C int,二进制转换为 ASCII

python - 有什么方法可以确定 Python 中的 cgi 请求来自哪个以太网端口?

c# - FireFox 和 IE9 尝试下载或显示 json-response 而不是让 javascript 解析它

c# - ChannelFactory 会发生故障吗?

python - 在 celery 工作人员内部存储数据的常见且明显的方式是什么?

python - 使用 joblib 将结果返回给父进程