网站建设教程 pdf,站长音效,排版网页设计教程,网页设计规范大全为什么需要C#调用python#xff1f;
有以下几个原因需要C#调用Python#xff1a; Python拥有丰富的生态系统#xff1a;Python有很多强大的第三方库和工具#xff0c;可以用于数据科学、机器学习、自然语言处理等领域。通过C#调用Python#xff0c;可以利用Python的生态系…为什么需要C#调用python
有以下几个原因需要C#调用Python Python拥有丰富的生态系统Python有很多强大的第三方库和工具可以用于数据科学、机器学习、自然语言处理等领域。通过C#调用Python可以利用Python的生态系统来完成一些特定的任务。 C#和Python的优势互补C#是一种高性能、静态类型的编程语言适合用于开发大型应用程序和高性能的系统。而Python则是一种动态类型的脚本语言适合用于快速开发原型和处理复杂的数据分析任务。通过C#调用Python可以充分发挥两者的优势。 C#和Python在不同领域的应用C#主要应用于Windows平台的开发而Python则可以用于各种平台包括Windows、Linux和Mac OS。通过C#调用Python可以在C#应用程序中使用Python的功能和特性实现更广泛的应用场景。
如何实现C#调用python脚本程序
方式一通过C#IronPython开源库
IronPython是一个基于.NET平台的Python解释器。它是使用C#编写的可以被集成到.NET应用程序中并且可以直接调用和使用.NET库和组件。IronPython提供了一个Python语言的实现同时具备了与.NET平台无缝集成的能力。
IronPython最初由微软开发并发布旨在提供一个Python解释器使Python开发人员能够利用.NET框架的优势。IronPython是完全兼容Python 2.7语法和语义的并且还支持一些Python 3的一些特性。IronPython可以通过.NET编译器将Python代码转换为托管代码并与.NET框架进行交互。
IronPython具有以下特点和优势
与.NET框架的深度集成IronPython可以直接与.NET库和组件进行交互可以轻松使用和调用.NET的功能和类库。动态语言的灵活性作为一种动态类型的脚本语言IronPython具有动态性和灵活性可以进行快速的原型开发和动态脚本编写。跨平台支持IronPython可以在Windows、Linux和Mac OS等多个平台上运行并且可以与不同平台的.NET应用程序集成。社区支持和活跃度IronPython拥有活跃的开源社区有大量的开发者和用户为其贡献代码和提供支持。
总之IronPython是一个具有.NET集成和跨平台支持的Python解释器可以在.NET平台开发中使用Python语言和功能。
IronPython.net / 缺点
1只支持到python 3.4的相关特性 和目前主流的python 3.9 3.103.11等版本相差甚远会导致很多python流行的开源库比如scikit-learn无法正常使用。 IronPython使用案例
NuGet安装IronPython test.py
def sayHi():print(hello you)def add(x,y):try:print(fadd {x}, {y})return x yexcept Exception as err:return str(err)def sum(arr):try:print(fsum {arr})sum 0for i in arr:sum ireturn sumexcept Exception as err:return str(err)
PythonScriptWindow.axml
Window x:ClassCallPythonDemos.PythonScriptWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:CallPythonDemosmc:IgnorabledTitlePython Script调用 Height450 Width800GridGrid.RowDefinitionsRowDefinition Heightauto/RowDefinition Heightauto/RowDefinition//Grid.RowDefinitionsGrid.ColumnDefinitionsColumnDefinition/ColumnDefinition//Grid.ColumnDefinitionsButton x:NamebtnCallPythonScript Content调用python脚本 Grid.Row0 Margin5 ClickbtnCallPythonScript_Click/Button x:NamebtnClearOutput Content清理输出 Grid.Row0 Grid.Column1 Margin5 ClickbtnClearOutput_Click/TextBlock Text输入参数: Grid.Row1 Margin5/TextBlock Text输出结果: Grid.Row1 Grid.Column1 Margin5/TextBox x:NametxtInputParam Grid.Row2 Margin5/RichTextBox x:NametxtOutputResult Grid.Row2 Grid.Column1 Margin5 HorizontalScrollBarVisibilityDisabled VerticalScrollBarVisibilityAuto IsReadOnlyTrueRichTextBox.DocumentFlowDocument//RichTextBox.Document/RichTextBox/Grid
/WindowPythonScriptWindow.axml.cs
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;namespace CallPythonDemos
{/// summary/// PythonScriptWindow.xaml 的交互逻辑/// /summarypublic partial class PythonScriptWindow : Window{public PythonScriptWindow(){InitializeComponent();}private void btnCallPythonScript_Click(object sender, RoutedEventArgs e){_RunTestByIronPython();}private void btnClearOutput_Click(object sender, RoutedEventArgs e){txtOutputResult.Document.Blocks.Clear();}private void _RunTestByIronPython(){ScriptEngine pyEngine Python.CreateEngine();dynamic testpy pyEngine.ExecuteFile(test.py);testpy.sayHi();var add testpy.add(3, 5);_WriteLog($add 方法的和是{add});int[] arr new int[3] { 2, 4, 6 };var sum testpy.sum(arr);_WriteLog($数组的和是{sum});}private void _WriteLog(string? log){Paragraph para new Paragraph() { Margin new Thickness(0) };para.Inlines.Add(new Run(log) { Foreground Brushes.Black });txtOutputResult.Document.Blocks.Add(para);}}
}运行效果 方式二 通过Process类来运行python解释器
优缺点
优点可以使用python当前的主流版本并且可以使用大部分的流行的开源库。
缺点只能通过命令行参数和控制台输出与python进行通信。
安装scikit-learn
pip install scikit-learn
gen_model.py
from sklearn import linear_model
if __name__ __main__:reg linear_model.LinearRegression()reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])print(coef_:, reg.coef_)print(intercept_:, reg.intercept_)print(done)
PythonScriptWindow.axml.cs
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;namespace CallPythonDemos
{/// summary/// PythonScriptWindow.xaml 的交互逻辑/// /summarypublic partial class PythonScriptWindow : Window{public PythonScriptWindow(){InitializeComponent();}private void btnCallPythonScript_Click(object sender, RoutedEventArgs e){//_RunTestByIronPython();_RunPythonScript();}private void btnClearOutput_Click(object sender, RoutedEventArgs e){txtOutputResult.Document.Blocks.Clear();}private void _RunTestByIronPython(){ScriptEngine pyEngine Python.CreateEngine();dynamic testpy pyEngine.ExecuteFile(test.py);testpy.sayHi();var add testpy.add(3, 5);_WriteLog($add 方法的和是{add});int[] arr new int[3] { 2, 4, 6 };var sum testpy.sum(arr);_WriteLog($数组的和是{sum});}/// summary/// 调用python脚本/// /summaryprivate void _RunPythonScript(){Process p new Process();p.StartInfo.FileName D:/my_project/Anaconda3/envs/jupyterlab_py310/python.exe;p.StartInfo.Arguments D:/my_project/first_board_debug/gen_model.py;p.StartInfo.UseShellExecute false;p.StartInfo.RedirectStandardOutput true;p.StartInfo.RedirectStandardInput true;p.StartInfo.RedirectStandardError true;p.StartInfo.CreateNoWindow true;_WriteLog($执行python脚本开始------------);p.Start();/*string output p.StandardOutput.ReadToEnd(); //读取控制台的输出信息p.WaitForExit(); // 等待外部程序进行完毕_WriteLog(output);_WriteLog($执行python脚本结束------------ exit code: {p.ExitCode});*/// 如果使用异步读取输出流python程序不会自动退出调用WaitForExit会阻塞// 必须自己根据返回来的字符串来决定程序是否已经执行完成p.BeginOutputReadLine();p.OutputDataReceived new DataReceivedEventHandler(outputDataReceived);}/// summary/// 输出执行python脚本的控制台信息/// /summaryprivate void outputDataReceived(object sender, DataReceivedEventArgs e){if (!string.IsNullOrEmpty(e.Data)){_WriteLog(e.Data);if (e.Data done){var p sender as Process;if(p!null){_WriteLog($执行python脚本结束);p.Close();}}}}private void _WriteLog(string? log){this.Dispatcher.Invoke(() {Paragraph para new Paragraph() { Margin new Thickness(0) };para.Inlines.Add(new Run(log) { Foreground Brushes.Black });txtOutputResult.Document.Blocks.Add(para);});}}
}运行效果