pyANSYS|C#调用python程序
来源:www.fangzhenxiu.com/post/7019473/
最近在用pyANSYS进行二次开发。之前使用PySide6做GUI界面,后面怎么看都觉得QT的原生界面实在是太丑了,专门做界面美化不熟悉而且又没那么多时间,考虑到程序只运行在Windows系统上,然后就换成C#配合DevExpress做界面了。漂亮的界面是搞出来了,但pyANSYS是基于python的,如何在C#下调用python编程的pyANSYS就成了个麻烦的问题。
网上搜索了一波,发现方法还不少,留此备查。
1 进程调用
将python程序打包成exe程序。常用的python打包工具有pyinstaller、Nuitka等,然后利用进程调用的方式启动exe程序。
这种方式最大的优点是将python环境一起打包到exe程序中,无需在目标机器上安装python依赖,这对于python程序中大量使用了第三方库的程序来说比较方便。
但此方式的缺点也很明显,首先打包后的exe程序非常大,启动的时候非常消耗内存,程序性能不好。
核心代码(原文地址:https://blog.csdn.net/qq_42063091/article/details/82418630):
using System.Diagnostics;namespaceWpfTest2{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>publicpartialclassMainWindow : Window{public MainWindow(){InitializeComponent();}private void Button_Click(object sender, RoutedEventArgs e){// exe程序的路径string pyexePath = @"main.exe";Process p = new Process();p.StartInfo.FileName = pyexePath;//需要执行的文件路径p.StartInfo.UseShellExecute = false; //必需p.StartInfo.RedirectStandardOutput = true;//输出参数设定p.StartInfo.RedirectStandardInput = true;//传入参数设定p.StartInfo.CreateNoWindow = true;p.StartInfo.Arguments = "2 3";//参数以空格分隔,如果某个参数为空,可以传入””p.Start();string output = p.StandardOutput.ReadToEnd();p.WaitForExit();//关键,等待外部程序退出后才能往下执行Console.Write(output);//输出p.Close();}}}
2 调用py文件
可以在c#中调用python.exe进程运行py文件。此方法需要在目标机器上安装python以及程序中所使用到的所有python库。
最大的优势是执行效率比调用exe要高一些,缺点是需要安装配置python环境。
核心代码:
private void Button_Click(object sender, RoutedEventArgs e){string[] strArr = newstring[2];//参数列表string sArguments = @"main.py";//这里是python的文件名字strArr[0] = "2";strArr[1] = "3";RunPythonScript(sArguments, "-u", strArr);}//调用python核心代码public static void RunPythonScript(string sArgName, string args = "", params string[] teps){Process p = new Process();// 获得python文件的绝对路径(将文件放在c#的debug文件夹中可以这样操作)string path = @"C:\Users\user\Desktop\test\" + sArgName;//没有配环境变量的话,可以写python.exe的绝对路径。如果配了,直接写"python.exe"即可p.StartInfo.FileName = @"D:\Python\envs\python3\python.exe";string sArguments = path;foreach (string sigstr in teps){sArguments += " " + sigstr;//传递参数}sArguments += " " + args;p.StartInfo.Arguments = sArguments;p.StartInfo.UseShellExecute = false;p.StartInfo.RedirectStandardOutput = true;p.StartInfo.RedirectStandardInput = true;p.StartInfo.RedirectStandardError = true;p.StartInfo.CreateNoWindow = true;p.Start();p.BeginOutputReadLine();p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);Console.ReadLine();p.WaitForExit();}//输出打印的信息static void p_OutputDataReceived(object sender, DataReceivedEventArgs e){if (!string.IsNullOrEmpty(e.Data)){AppendText(e.Data + Environment.NewLine);}}public delegate void AppendTextCallback(string text);public static void AppendText(string text){//此处在控制台输出.py文件print的结果Console.WriteLine(text);}
测试的python代码:
import numpy as npimport sysdef multiplication(a,b):return a*bdef func(a,b):result=np.sqrt(multiplication(int(a),int(b)))return resultif __name__ == '__main__':print(func(sys.argv[1],sys.argv[2]))
3 使用ironPython
没有使用过,据说可以在C#中直接调用python,但这种方法对numpy之类的第三方库支持很差。pyansys使用了大量的科学计算库,想想还是算了。
4 使用动态链接库
有说可以利用c/c++程序调用python文件,然后将其做成动态链接库,在c#中调用此dll。想想都觉得麻烦,算了。
5 利用c#的第三方库
这里有篇文章:https://juejin.cn/post/7205449056071123005
里面介绍使用pythonnet库来实现c#对python程序的调用。看介绍效果还不错,不过感觉太麻烦,以后有时间再尝试。
扫码进群记得备注:城市、昵称和技术方向。
👇扫描下方二维码,逆袭成长👇