首页 > 解决方案 > 从 Winform C# 应用程序调用 Python 脚本

问题描述

我想从我的 winform C# 应用程序中调用 Python 脚本。我检查了一些解决方案并遵循以下方法。一种使用进程间通信,一种使用 IronPython

方法 1:使用进程间通信

private void BtnSumPy_Click(object sender, EventArgs e)
    {
        string python = @"C:\Programs\Python\Python37-32\python.exe";

        // python app to call 
        string myPythonApp = @"C:\mypath\\SamplePy\SamplePy2\SamplePy2.py";

        // dummy parameters to send Python script 
        int x = 3;
        int y = 4;

        // Create new process start info 
        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

        // make sure we can read the output from stdout 
        myProcessStartInfo.UseShellExecute = false;
        myProcessStartInfo.RedirectStandardOutput = true;

        // start python app with 3 arguments  
        // 1st arguments is pointer to itself,  
        // 2nd and 3rd are actual arguments we want to send 
        myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y;

        Process myProcess = new Process();
        // assign start information to the process 
        myProcess.StartInfo = myProcessStartInfo;

        // start the process 
        myProcess.Start();

        // Read the standard output of the app we called.  
        // in order to avoid deadlock we will read output first 
        // and then wait for process terminate: 
        StreamReader myStreamReader = myProcess.StandardOutput;
        string myString = myStreamReader.ReadLine();

        /*if you need to read multiple lines, you might use: 
            string myString = myStreamReader.ReadToEnd() */

        // wait exit signal from the app we called and then close it. 
        myProcess.WaitForExit();
        myProcess.Close();           

        lblAns.Text = myString;
    }

上述方法的问题是 Python.exe 也必须安装在本地机器上,因为 winform 应用程序将在系统上本地运行。

方法 2:使用 IronPython

private void BtnJsonPy_Click(object sender, EventArgs e)
    {
        // 1. Create Engine
        var engine = Python.CreateEngine();

        //2. Provide script and arguments
        var script = @"C:\Users\simeh\source\HDFC\repos\SamplePy\SamplePy2\SamplePy2.py"; // provide full path
        var source = engine.CreateScriptSourceFromFile(script);

        // dummy parameters to send Python script 
        int x = 3;
        int y = 4;

        var argv = new List<string>();
        argv.Add("");
        argv.Add(x.ToString());
        argv.Add(y.ToString());

        engine.GetSysModule().SetVariable("argv", argv);

        //3. redirect output
        var eIO = engine.Runtime.IO;

        var errors = new MemoryStream();
        eIO.SetErrorOutput(errors, Encoding.Default);

        var results = new MemoryStream();
        eIO.SetOutput(results, Encoding.Default);

        //4. Execute script
        var scope = engine.CreateScope();

        var lib = new[]
        {
            "C:\\path\\SamplePy\\packages\\IronPython.2.7.9\\lib",
            "C:\\path\\SamplePy\\packages\\IronPython.2.7.9",
        };

        engine.SetSearchPaths(lib);
        engine.ExecuteFile(script, scope);
        //source.Execute(scope);

        //5. Display output
        string str(byte[] x1) => Encoding.Default.GetString(x1);

        Console.WriteLine("Errrors");
        Console.WriteLine(str(errors.ToArray()));
        Console.WriteLine();
        Console.WriteLine("Results");
        Console.WriteLine(str(results.ToArray()));
    }

我遇到的问题是我不断收到诸如“Json 模块错误”或“PIL 模块错误”之类的错误

我在某处读到 PIL 目前无法与 IronPython 一起使用,因为它使用了本机 C 库。

python 脚本具有 ML 逻辑并使用 OCR 等进行图像处理,因此需要 PIL,这在 IronPython 中无法完成。

因此,有关如何从 Winform C# 应用程序调用 Python 脚本的任何更好的方法或方法或建议。

提前致谢!!!..

标签: c#python-3.xwinformsprocessironpython

解决方案


“导入错误”的解决方案在这里打开 cmd 并转到 AppData>Local>Programs>Python>Python37-32 然后写这个

pip3 install json

如果你想从 c# 运行 .py 文件,导入模块必须在 python.exe 的目录中

例如,我将 cv2 和其他库导入 Python37-32 目录。在此之后,我的程序运行良好。

这是我的代码:

timer1.Enabled = true;
                    progressBar1.Value += 10;
                    string myPythonApp = "C://Users//giris//Desktop//staj_proje_son//main.py";
                    string cmdArguments = "/c \"python " + myPythonApp + " " + "--ogrencioptik " + textBox2.Text + " " + "--cevapkagidi " + textBox1.Text + " " + "--sonuckayit " + textBox3.Text + "\"";
                    ProcessStartInfo start = new ProcessStartInfo();
                    start.FileName = "cmd.exe";
                    start.UseShellExecute = false;
                    start.WorkingDirectory = "C://Users//giris//Desktop//staj_proje_son//";
                    start.Arguments = cmdArguments;
                    start.RedirectStandardOutput = false;
                    start.RedirectStandardError = true;
                    start.CreateNoWindow = true;
                    Process process = Process.Start(start);
                    timer1.Start();
                    process.WaitForExit();
                    timer1.Stop();
                    timer1.Enabled = false;
                    progressBar1.Value = 100;
                    MessageBox.Show("İşlem Bitti");
                    button3.Enabled = true;

注意:所有的 textbox.text 都是文件夹的路径。


推荐阅读