静怡的白桦林 發表於 2020-3-20 11:20:00

一 、C#调用Python的使用总结

<p>  <span style="font-size: 18px"><strong><span style="font-family: &quot;Microsoft YaHei&quot;">由于项目的需要,需要通过C#调用Python文件(算法)。之前接触不多,在测试试验的过程遇到了挺多坑的,在这里将试验的过程和结果在这里总结一下。</span></strong></span></p>
<p><span style="font-size: 16px">一.使用IronPython作为移植的依赖库,直接调用python文件的函数接口。</span></p>
<p>  百度词条:IronPython&nbsp;是一种在&nbsp;NET&nbsp;和&nbsp;Mono&nbsp;上实现的 Python 语言,由 Jim Hugunin(同时也是&nbsp;Jython&nbsp;创造者)所创造。它的诞生是为了将更多的动态语音移植到NET Framework上。</p>
<p>  通过简单的C#代码实现对python文件内部函数的调用。这种方法可以说是最简单直接的,但是,问题来了。<span style="text-decoration: line-through">IronPython的发布截止到2011年3月,就是说后面就没有进行开发和更新了。Python的设计应用日新月异,相关的库的设计和开发层出不穷。不能支持很多第三方库的引用和加载是这种方法最大的缺陷,简单的代码我们也没必要专门写成python文件去给C#调用,C#自己都可以写。</span></p>
<p><span style="text-decoration: line-through">  这种方法建议大伙就别尝试了,浪费时间。</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp;PS:(更正,IronPython还是有继续更新发布的,最新版本是 2.7.10,发布于April 27, 2020。可以到网页进行了解https://ironpython.net/,谢谢三楼纠正)</p>
<p>&nbsp;</p>
<p><span style="font-size: 16px">二.使用c++程序调用python文件,然后将其做成动态链接库(dll),在c#中调用此dll文件。</span></p>
<p>  这种方法是最开始使用的,但由于运行速度太慢,所以排除使用,所以后续才有第三种方法。详细如何操作,这里没研究过就不介绍了(别人开发接口的dll,直接使用没去了解具体操作)。</p>
<p>&nbsp;</p>
<p><span style="font-size: 16px">三.需要安装python安装包和库环境,利用c#命令行,调用.py文件执行(最终使用方法)</span></p>
<p>  这种方法:通过C#命令行调用.py文件 ==&nbsp;通过python.exe&nbsp;打开.py文件</p>
<p>  他的适用性强,你只要保证你的.py程序能够通过python.exe打开,使用就不会有大问题,同时还有一些需要注意的点。</p>
<p>  (1)文件路径不能使用相对路径(例:path = ./文件名 或者path = 文件名 ),会报错,这一块我不清楚是否别人没遇到,反正我的话是一直会报这种错误。</p>
<p>  解决方法也很简单,要么用绝对路径,要么导入os库,通过os.path.dirname(__file__)可以得到当前文件的路径,即path =&nbsp;os.path.dirname(__file__) + '\文件名'</p>
<p>  (2)路径间隔需要用/代替\;同时“\\”作为输入参数偶尔也会有出现异常的情况,原因不明。个人建议将输入路径参数全部提前替换</p>
<p>  (3)不能调用py文件的接口,函数方法</p>
<p>  (4)最好在程序前附加异常检测处理(try,exception),便于获取异常(C#调用Python偶尔库,或者一些路径会有异常,导致直接运行失败)</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(128, 0, 128, 1)">__name__</span>==<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">__main__</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">代码行</span>
      a = 1
    <span style="color: rgba(0, 0, 255, 1)">except</span><span style="color: rgba(0, 0, 0, 1)"> Exception as err:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">捕捉异常</span>
      str1 = <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">default:</span><span style="color: rgba(128, 0, 0, 1)">'</span> +<span style="color: rgba(0, 0, 0, 1)"> str(err)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 代码运行正常</span>
      str1 = <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Code are operating normally.</span><span style="color: rgba(128, 0, 0, 1)">"</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span>(str1)</pre>
</div>
<p>&nbsp;</p>
<p><span style="font-size: 16px"><strong>  <span style="font-size: 15px">测试步骤如下:</span></strong></span></p>
<p>  1、下载安装python,安装环境库</p>
<p>  我是通过Notepad++进行python程序编写,安装库直接使用python自带pip进行安装。通过CMD直接进行安装</p>
<p>  (1)下面介绍几个常用的pip操作和如何安装库</p>
<p>    显示pip的安装列表:pip list<br>    安装库:pip install 库名<br>    安装对应版本的库:pip install --upgrade 库名==版本号<br>    卸载库:pip uninstall 库名</p>
<p>  (2)等待安装完毕即可</p>
<p>  (3)注意网速问题,如果网速不好建议直接下载对应库的离线安装包(注意)</p>
<p><img src="https://img2020.cnblogs.com/blog/1962164/202003/1962164-20200320104333477-414240675.png" alt="" width="798" height="371"></p>
<p>&nbsp;</p>
<p>  2、通过VS编写一个简单的window窗口进行测试,C#界面和代码如下</p>
<p>  有一些需要注意的地方,首先:文件路径不能存在空格;输入参数是路径的建议全部替换'\\'为'/';</p>
<p><img src="https://img2020.cnblogs.com/blog/1962164/202003/1962164-20200320111814124-744876250.png" alt="" width="295" height="176"></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Collections.Generic;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.ComponentModel;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Data;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Diagnostics;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Drawing;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.IO;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Linq;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Text;
</span><span style="color: rgba(0, 0, 255, 1)">using</span><span style="color: rgba(0, 0, 0, 1)"> System.Windows.Forms;

</span><span style="color: rgba(0, 0, 255, 1)">namespace</span><span style="color: rgba(0, 0, 0, 1)"> ToolApp
{
    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">partial</span> <span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)"> Example : Form
    {
      </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> Process progressTest;

      </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Example()
      {
            InitializeComponent();
      }

      </span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">void</span> buttonAdd_Click(<span style="color: rgba(0, 0, 255, 1)">object</span><span style="color: rgba(0, 0, 0, 1)"> sender, EventArgs e)
      {
            </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">
            {
                </span><span style="color: rgba(0, 0, 255, 1)">string</span> path = Application.StartupPath + <span style="color: rgba(128, 0, 0, 1)">@"</span><span style="color: rgba(128, 0, 0, 1)">\Add.py</span><span style="color: rgba(128, 0, 0, 1)">"</span>;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">py文件路径</span>
                <span style="color: rgba(0, 0, 255, 1)">int</span> a = Convert.ToInt32(<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.textBox1.Text);
                </span><span style="color: rgba(0, 0, 255, 1)">int</span> b = Convert.ToInt32(<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.textBox2.Text);
                StartTest(path, a, b);
            }
            </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)">(Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
      }
      </span><span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;summary&gt;</span>
      <span style="color: rgba(128, 128, 128, 1)">///</span> 开始测试
      <span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;/summary&gt;</span>
      <span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;param name="pathAlg"&gt;</span><span style="color: rgba(0, 128, 0, 1)">py文件路径</span><span style="color: rgba(128, 128, 128, 1)">&lt;/param&gt;</span>
      <span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;param name="a"&gt;</span><span style="color: rgba(0, 128, 0, 1)">加数a</span><span style="color: rgba(128, 128, 128, 1)">&lt;/param&gt;</span>
      <span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;param name="b"&gt;</span><span style="color: rgba(0, 128, 0, 1)">加数b</span><span style="color: rgba(128, 128, 128, 1)">&lt;/param&gt;</span>
      <span style="color: rgba(128, 128, 128, 1)">///</span> <span style="color: rgba(128, 128, 128, 1)">&lt;returns&gt;&lt;/returns&gt;</span>
      <span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">bool</span> StartTest(<span style="color: rgba(0, 0, 255, 1)">string</span> pathAlg, <span style="color: rgba(0, 0, 255, 1)">int</span> a, <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> b)
      {
            </span><span style="color: rgba(0, 0, 255, 1)">bool</span> state = <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;

            </span><span style="color: rgba(0, 0, 255, 1)">if</span> (!<span style="color: rgba(0, 0, 0, 1)">File.Exists(pathAlg))
            {
                </span><span style="color: rgba(0, 0, 255, 1)">throw</span> <span style="color: rgba(0, 0, 255, 1)">new</span> Exception(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">The file was not found.</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
                </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">;
            }
            </span><span style="color: rgba(0, 0, 255, 1)">string</span> sArguments =<span style="color: rgba(0, 0, 0, 1)"> pathAlg;
            sArguments </span>+= <span style="color: rgba(128, 0, 0, 1)">"</span> <span style="color: rgba(128, 0, 0, 1)">"</span> + a.ToString() + <span style="color: rgba(128, 0, 0, 1)">"</span> <span style="color: rgba(128, 0, 0, 1)">"</span> + b.ToString() + <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)"> -u</span><span style="color: rgba(128, 0, 0, 1)">"</span>;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Python文件的路径用“/”划分比较常见</span>
<span style="color: rgba(0, 0, 0, 1)">
            ProcessStartInfo start </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> ProcessStartInfo();
            start.FileName </span>= <span style="color: rgba(128, 0, 0, 1)">@"</span><span style="color: rgba(128, 0, 0, 1)">python.exe</span><span style="color: rgba(128, 0, 0, 1)">"</span>;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">环境路径需要配置好</span>
            start.Arguments =<span style="color: rgba(0, 0, 0, 1)"> sArguments;
            start.UseShellExecute </span>= <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">;
            start.RedirectStandardOutput </span>= <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;
            start.RedirectStandardInput </span>= <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;
            start.RedirectStandardError </span>= <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;
            start.CreateNoWindow </span>= <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;

            </span><span style="color: rgba(0, 0, 255, 1)">using</span> (progressTest =<span style="color: rgba(0, 0, 0, 1)"> Process.Start(start))
            {
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 异步获取命令行内容</span>
<span style="color: rgba(0, 0, 0, 1)">                progressTest.BeginOutputReadLine();
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 为异步获取订阅事件</span>
                progressTest.OutputDataReceived += <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> DataReceivedEventHandler(outputDataReceived);
            }
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> state;
      }

      </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> outputDataReceived(<span style="color: rgba(0, 0, 255, 1)">object</span><span style="color: rgba(0, 0, 0, 1)"> sender, DataReceivedEventArgs e)
      {
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> (!<span style="color: rgba(0, 0, 255, 1)">string</span><span style="color: rgba(0, 0, 0, 1)">.IsNullOrEmpty(e.Data))
            {
                </span><span style="color: rgba(0, 0, 255, 1)">this</span>.Invoke(<span style="color: rgba(0, 0, 255, 1)">new</span> Action(() =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                  </span><span style="color: rgba(0, 0, 255, 1)">this</span>.textBox3.Text =<span style="color: rgba(0, 0, 0, 1)"> e.Data;
                }));
            }
      }
    }
}</span></pre>
</div>
<p>&nbsp;</p>
<p>  3、通过Notepad++编写一个简单的加法函数,调用Python文件代码如下,导入栏导入一些比较第三方的库(为了测试看看第三方库的导入是否正常)</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> numpy
</span><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> os
</span><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> sys

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> Add(a,b):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> a+<span style="color: rgba(0, 0, 0, 1)">b

</span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(128, 0, 128, 1)">__name__</span>==<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">__main__</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">代码行</span>
      a = int(sys.argv)
      b </span>= int(sys.argv)
      c </span>=<span style="color: rgba(0, 0, 0, 1)"> Add(a,b)
    </span><span style="color: rgba(0, 0, 255, 1)">except</span><span style="color: rgba(0, 0, 0, 1)"> Exception as err:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">捕捉异常</span>
      str1 = <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">default:</span><span style="color: rgba(128, 0, 0, 1)">'</span> +<span style="color: rgba(0, 0, 0, 1)"> str(err)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
      </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 代码运行正常</span>
      str1 =<span style="color: rgba(0, 0, 0, 1)"> c
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(str1)</pre>
</div>
<p>&nbsp;</p>
<p>  4、生成成功,通过界面输入两组数字,点击测试,可以成功得到结果,效果如下</p>
<p>&nbsp;<img src="https://img2020.cnblogs.com/blog/1962164/202003/1962164-20200320110930305-723194238.png" alt="" width="326" height="194">&nbsp;<img src="https://img2020.cnblogs.com/blog/1962164/202003/1962164-20200320111300593-858387878.png" alt="" width="327" height="194"></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>———————————————————————————————————————————</p>
<p>如何使用IronPython,参考链接:https://www.cnblogs.com/ligiggy/p/11471071.html</p>
<p>四种方法调用,参考链接:https://blog.csdn.net/qq_42063091/article/details/82418630</p><br><br>
来源:https://www.cnblogs.com/ludage/p/12461403.html
頁: [1]
查看完整版本: 一 、C#调用Python的使用总结