首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Winform C#应用程序调用Python脚本

从Winform C#应用程序调用Python脚本
EN

Stack Overflow用户
提问于 2019-07-03 18:35:21
回答 1查看 2.4K关注 0票数 1

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

方法1:使用进程间通信

代码语言:javascript
复制
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

代码语言:javascript
复制
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 module error”或“PIL module error”这样的错误。

我在某处读到,PIL目前不能与IronPython一起工作,因为它使用的是本机C库。

python脚本具有ML逻辑,并使用OCR等进行图像处理,因此需要PIL,这在IronPython中是做不到的。

所以如何从Winform C#应用程序调用Python脚本有任何更好方法或方法或建议。

提前感谢!..

EN

回答 1

Stack Overflow用户

发布于 2019-07-03 19:05:15

'import error‘的解决方案在这里,打开cmd,进入AppData>Local>Programs>Python>Python37-32,然后写下

代码语言:javascript
复制
pip3 install json

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

例如,ı将cv2和其他库导入到Python37-32目录。在这之后,我的程序运行得很好。

这是我的代码:

代码语言:javascript
复制
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都是文件夹的路径。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56868185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档