当前位置:   article > 正文

深度学习平台demo(一)- C#如何调用python文件_ironpython深度学习

ironpython深度学习

了解完keras的知识点后,接下来演示用c#做界面,底层用python来做一个深度学习的平台。对于Demo程序依赖的python(Anaconda环境)、cuda、cudnn基础环境的配置,这里不再赘叙,可以借鉴我较早的博客,win10, win11下的环境配置可借鉴,不能照搬。

本系列博客所用环境如下:

Anaconda3-5.2.0-Windows-x86_64.exe

python3.6.5

tensorflow 2.3.1

cuda 10.1

cudnn 7.6

如上环境也是我写如下博客时所用环境,一些详情感兴趣的童鞋可以移步此篇博客看下。

tensorflow1.x代码转换到tensorflow2.x-CSDN博客

 

这篇博客先不戳核心,暂时先回顾下怎么用c#来调用python。我亲手实验了如下三种方式,然后引出我后面做深度学习平台要用的方式。

方式一:通过IronPython库来实现

新建了一个winform项目,如下选择管理NuGet程序包选项

在浏览中选择IronPython包,选择安装即可

安装完毕后相关dll会自动被引用到该工程中,不需要手动添加

如下是我的设计界面(此界面包括了三种方式测试,接下来会一步步的展示

comboBox1中设置的选项如下(+,-,*)表示三种运算

按钮回调函数中代码如下:

  1. ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
  2. ScriptEngine pyEngine = scriptRuntime.GetEngine("python");
  3. ScriptSource source = pyEngine.CreateScriptSourceFromFile("test_IronPython1.py");//设置脚本文件
  4. ScriptScope scope = pyEngine.CreateScope();
  5. try
  6. {
  7. scope.SetVariable("arg1", Convert.ToInt32(textBox1.Text));
  8. scope.SetVariable("arg2", Convert.ToInt32(textBox2.Text));
  9. scope.SetVariable("arg3", comboBox1.SelectedIndex + 1);
  10. }
  11. catch(Exception)
  12. {
  13. MessageBox.Show("输入有误");
  14. }
  15. source.Execute(scope);
  16. label1.Text = scope.GetVariable("result").ToString();

这里test_IronPython1.py中代码如下:

  1. num1=arg1
  2. num2=arg2
  3. op=arg3
  4. if op==1:
  5. result=num1+num2
  6. elif op==2:
  7. result=num1-num2
  8. elif op==3:
  9. result=num1*num2
  10. else:
  11. result=num1*1.0/num2

该python文件中没有设置函数,直接以脚本的形式呈现,但在上面的c#代码中,可以通过getVariable来获取指定变量的内容而可以进行交互。执行效果如下:

输入加数和被加数后,点击按钮,便可以获得数据

下面展示通过调用python文件中的函数来执行功能代码

test_ironpython_function按钮的回调函数代码如下:

  1. ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();//创建Python解释器对象
  2. dynamic py = pyEngine.ExecuteFile(@"test_IronPython2.py");//读取脚本文件
  3. string reStr = py.cal(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text), comboBox1.SelectedIndex + 1);//调用脚本文件中对应的函数
  4. label1.Text = "";
  5. label1.Text = reStr;
  6. reStr = py.main();//调用脚本文件中对应的函数
  7. MessageBox.Show(reStr);
  8. //或者
  9. ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //创建一下运行环境
  10. dynamic obj = pyRuntime.UseFile(@"test_IronPython2.py"); //调用一个Python文件
  11. string Str2 = obj.main2(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text), comboBox1.SelectedIndex + 1);//调用脚本文件中对应的函数
  12. MessageBox.Show(Str2);

代码中‘’//或者"上面代码和下面代码是两种调用函数的实现方式,效果是一样的。

代码中"//或者“上面的代码测试了两个函数中共享变量的效果,这种方式下,是可以通过共享变量让不同函数中代码发生关联。test_IronPython2.py中代码如下:

  1. global s
  2. s=-1;
  3. def cal(num1,num2,op):
  4. global s
  5. s=num1
  6. if op==1:
  7. result=num1+num2
  8. elif op==2:
  9. result=num1-num2
  10. elif op==3:
  11. result=num1*num2
  12. else:
  13. result=num1*1.0/num2
  14. return str(result)
  15. def main():
  16. global s
  17. return str(s)
  18. def main2(arg1,arg2,arg3):
  19. try:
  20. num1=arg1
  21. num2=arg2
  22. op=arg3
  23. return cal(num1,num2,op)
  24. except Exception as err:
  25. return str(err)

执行效果如下:

点击确定后

二. 通过程序设置命令行执行py文件方式

test_python_exe按钮的回调函数如下:

  1. try
  2. {
  3. Process p = new Process();
  4. string path = @"D:\mycode\test_python_exe.py";//待处理python文件的路径,本例中放在debug文件夹下
  5. string sArguments = path;
  6. ArrayList arrayList = new ArrayList();
  7. arrayList.Add(Convert.ToInt32(textBox1.Text));
  8. arrayList.Add(Convert.ToInt32(textBox2.Text));
  9. arrayList.Add(comboBox1.SelectedIndex + 1);
  10. foreach (var param in arrayList)//添加参数
  11. {
  12. sArguments += " " + param;
  13. }
  14. p.StartInfo.FileName = @"C:\Anaconda3\python.exe"; //python 3.x的安装路径
  15. p.StartInfo.Arguments = sArguments;//python命令的参数
  16. p.StartInfo.UseShellExecute = false;
  17. p.StartInfo.RedirectStandardOutput = true;
  18. p.StartInfo.RedirectStandardInput = true;
  19. p.StartInfo.RedirectStandardError = true;
  20. p.StartInfo.CreateNoWindow = true;
  21. p.Start();//启动进程
  22. p.BeginOutputReadLine();
  23. p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
  24. p.Close();
  25. // p.WaitForExit();
  26. MessageBox.Show("执行完毕!");
  27. }
  28. catch(Exception ec)
  29. {
  30. Console.WriteLine(ec);
  31. }

test_python_exe.py中代码如下:

  1. import sys
  2. def cal(num1,num2,op):
  3. if op==1:
  4. result=num1+num2
  5. elif op==2:
  6. result=num1-num2
  7. elif op==3:
  8. result=num1*num2
  9. else:
  10. result=num1 - num2
  11. return str(result)
  12. if __name__=='__main__':
  13. print(cal(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])))

这里推荐是可以先在cmd环境下把所设置的命令行语句跑下,验证下py文件里有无错,及py路径是否设置错,方便排查问题,执行效果如下:

三. 把py文件打包成exe文件,然后再通过命令行方式直接把exe文件跑起来

test_pyinstall按钮的回调函数中代码如下:

  1. try
  2. {
  3. Process p = new Process();
  4. string sArguments = "";
  5. ArrayList arrayList = new ArrayList();
  6. arrayList.Add(Convert.ToInt32(textBox1.Text));
  7. arrayList.Add(Convert.ToInt32(textBox2.Text));
  8. arrayList.Add(comboBox1.SelectedIndex + 1);
  9. foreach (var param in arrayList)//添加参数
  10. {
  11. sArguments += " " + param;
  12. }
  13. p.StartInfo.FileName = @"D:\mycode\dist\test_python_exe.exe"; //python3.x的安装路径
  14. p.StartInfo.Arguments = sArguments;//python命令的参数
  15. p.StartInfo.UseShellExecute = false;
  16. p.StartInfo.RedirectStandardOutput = true;
  17. p.StartInfo.RedirectStandardInput = true;
  18. p.StartInfo.RedirectStandardError = true;
  19. p.StartInfo.CreateNoWindow = true;
  20. p.Start();//启动进程
  21. string output = p.StandardOutput.ReadToEnd();
  22. Console.WriteLine(output);
  23. p.Close();
  24. MessageBox.Show("执行完毕!");
  25. }
  26. catch (Exception ec)
  27. {
  28. Console.WriteLine(ec);
  29. }

没有安装pyinstaller的童鞋,需要手动安装下:

执行命令:pip install pyinstaller可以实现安装,中间如果出现报错module 'enum' has no attribute 'IntFlag'

表示当前自带enum34版本和安装pyinstaller中需要的enum34版本不一致,需要先卸载再安装pyinstaller

安装完毕后执行

pyinstaller -F test_python_exe.py

便可以将上面的py文件生成一个可执行exe文件

执行上面的c#代码,效果如下:

如上三种方式介绍完毕。

三种方式中,第一种当前只支持python2.x系列,无法满足深度学习所需要的的python 3.x的要求,故采用第二种方式,第三种方式需要打包操作,且执行效率慢。

下面一篇博客会在第二种方式基础上实现c#调用python实现训练和预测的功能。预测阶段如何让python的进程和c#进程之间互传图像数据,一张张图片通过python进程预测结果,并把预测结果给到c#进程是该博客会重点介绍的地方。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/478508
推荐阅读
相关标签
  

闽ICP备14008679号