IronPython是一種在 .NET及 Mono上的 Python實現(xiàn),由微軟的 Jim Hugunin所發(fā)起,是一個開源的項目,基于微軟的 DLR引擎。IronPython的在CodePlex上的主頁:http://ironpython.codeplex.com/
使用場景:
如果你的小伙伴會寫Python腳本,而且已經(jīng)實現(xiàn)大部分項目的功能不需要再用C# 實現(xiàn)?,F(xiàn)在缺少窗體,此時Python+C#的組合就可以完美的結(jié)局問題啦!
示例:
借由IronPython,就可以利用.NET執(zhí)行存儲在Python腳本中的代碼段。下面通過簡單的示例說明如何應(yīng)用C#調(diào)用Python腳本。
1、在VS中新建窗體項目:IronPythonDemo
2、VS的菜單中打開“Nuget程序包管理器”

3、搜索IronPython程序包并安裝

4、在exe程序所在文件夾下(此例中為"./IronPythonDemo/IronPythonDemo/bin/Debug"),創(chuàng)建Python腳本?;?qū)F(xiàn)有的腳本拷貝到該目錄下。Python示例腳本實現(xiàn)求兩個數(shù)的四則運算:
num1=arg1 num2=arg2 op=arg3 if op==1: result=num1+num2 elif op==2: result=num1-num2 elif op==3: result=num1*num2 else: result=num1*1.0/num2
5、修改工程的配置文件App.config如下:
其中microsoft.scripting節(jié)點中設(shè)置了IronPython語言引擎的幾個屬性。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting"/> </configSections> <microsoft.scripting> <languages> <language names="IronPython;Python;py" extensions=".py" displayName="Python" type="IronPython.Runtime.PythonContext, IronPython"/> </languages> </microsoft.scripting> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
6、 繪制窗體如下:
7、編寫計算的函數(shù):
private void btnCalculate_Click(object sender, EventArgs e) { ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); ScriptEngine rbEng = scriptRuntime.GetEngine("python"); ScriptSource source = rbEng.CreateScriptSourceFromFile("IronPythonDemo.py");//設(shè)置腳本文件 ScriptScope scope = rbEng.CreateScope(); try { //設(shè)置參數(shù) scope.SetVariable("arg1",Convert.ToInt32(txtNum1.Text)); scope.SetVariable("arg2", Convert.ToInt32(txtNum2.Text)); scope.SetVariable("arg3", operation.SelectedIndex+1); } catch (Exception) { MessageBox.Show("輸入有誤。"); } source.Execute(scope); labelResult.Text = scope.GetVariable("result").ToString(); } 8、編譯運行可得計算結(jié)果(此處未做輸入的檢查)
以上就是C#調(diào)用Python腳本的簡單方法,希望對大家的學習有所幫助。





















