Python是AI领域最主流的编程语言,没有之一。在应用程序开发领域,通常不会选择Python语言。如果在应用开发过程中涉及到人工智能算法,就不可避免地要面对跨语言交流的问题。今天介绍一种在C#中执行Python脚本的方式,当然还有其他方式。需要安装python安装包和库环境,使用c#命令行调用.py文件执行 本方法:通过C#命令行调用.py文件==通过python打开.py文件.exe 其他适用性强,只要保证你的.py程序能被python.exe打开,使用起来不会有太大问题。同时,也有一些需要注意的地方。 (1)文件路径不能使用相对路径(例如:path=./filename或path=filename),会报错。不知道其他人有没有遇到过,反正我老是报这种错误。 解决方法也很简单,要么使用绝对路径,要么导入os库,通过os.path.dirname(__file__)即可获取当前文件的路径,即path=os.path。dirname(__file__)+'\文件名' (2)路径间隔需要用/代替;同时,“\”作为入参偶尔会出现异常情况,原因不明。个人建议提前把输入的路径参数全部替换掉?? (3)py文件的接口调用不了,函数方法 (4)最好加上异常检测处理(试试,exception)程序前为了方便获取异常(C#偶尔会调用Python库,或者某些路径会出现异常,导致直接运行失败)准备一个简单的Winform程序和Python脚本。Winform程序如下:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;使用System.Windows.Forms;命名空间CsharpCallPython{publicpartialclassForm1:Form{privateProcessprogressTest;publicForm1(){InitializeComponent();}privatevoidbtnAdd_Click(objectsender,EventArgse){try{//stringpath=Application.StartupPath+@"\CsharpCallPython.py";//py文件路径";stringpath="F:\\study\\mycode\\python\\PythonTest\\flaskdemo\\mypthondemo.py";inta=Convert.ToInt32(txtA.Text);intb=Convert.ToInt32(txtB.Text);StartTest(path,a,b);}赶上(异常前){MessageBox.Show(ex.Message);}}publicvoidoutputDataReceived(objectsender,DataReceivedEventArgse){if(!string.IsNullOrEmpty(e.Data)){this.Invoke(newAction(()=>{this.txtResult.Text=e.Data;}));}}publicboolStartTest(stringpathAlg,inta,intb){boolstate=true;if(!File.Exists(pathAlg)){thrownewException("找不到文件。");返回假;}字符串sArguments=pathAlg;sArguments+=""+a.ToString()+""+b.ToString()+"-u";//用"/"分隔的Python文件路径很常见。ProcessStartInfo开始=newProcessStartInfo();start.FileName=@"D:\Python36\python.exe";//环境路径需要配置Python的实际安装路径。start.Arguments=sArguments;开始.UseShellExecute=false;开始.RedirectStandardOutput=true;开始.RedirectStandardInput=true;开始.RedirectStandardError=true;start.CreateNoWindow=true;using(progressTest=Process.Start(start)){//异步获取命令行内容progressTest.BeginOutputReadLine();//异步获取订阅事件progressTest.OutputDataReceived+=newDataReceivedEventHandler(outputDataReceived);}返回状态;}}}Python脚本如下:#-*-coding:utf-8-*-"""FileName:PythonTestAuthor:MichaelDate:2022/10/27"""importnumpyimportosimportsysdefAdd(a,b):returna+bif__name__=='__main__':try:#代码行a=int(sys.argv[1])b=int(sys.argv[2])c=Add(a,b)exceptExceptionaserr:#捕获异常str1='default:'+str(err)else:#代码运行正常str1=cprint(str1)从上面的代码不难看出,这是一个实现简单加法运算的函数。为了认真实现Python脚本在C#中的可行性,我写了一个Python脚本来实现两个数。求和运算。运行Winform程序,很快得到结果:【结论】:这样就可以实现Python脚本的最终运行了。但这不是通常处理跨语言交流的方式。因此,还是有必要好好研究一下RPC框架的。
