C#調用Python指令碼的簡單樣本_C#教程

來源:互聯網
上載者:User

IronPython是一種在 .NET及 Mono上的 Python實現,由微軟的 Jim Hugunin所發起,是一個開源的項目,基於微軟的 DLR引擎。IronPython的在CodePlex上的首頁:http://ironpython.codeplex.com/ 

使用情境:

如果你的小夥伴會寫Python指令碼,而且已經實現大部分項目的功能不需要再用C# 實現。現在缺少表單,此時Python+C#的組合就可以完美的結局問題啦!

樣本:
藉由IronPython,就可以利用.NET執行儲存在Python指令碼中的程式碼片段。下面通過簡單的樣本說明如何應用C#調用Python指令碼。

1、在VS中建立表單項目:IronPythonDemo

2、VS的菜單中開啟“Nuget封裝管理員”

3、搜尋IronPython程式包並安裝

4、在exe程式所在檔案夾下(此例中為".\IronPythonDemo\IronPythonDemo\bin\Debug"),建立Python指令碼。或將現有的指令碼拷貝到該目錄下。Python樣本指令碼實現求兩個數的四則運算:

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節點中設定了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、編寫計算的函數:

private void btnCalculate_Click(object sender, EventArgs e)   {    ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();    ScriptEngine rbEng = scriptRuntime.GetEngine("python");    ScriptSource source = rbEng.CreateScriptSourceFromFile("IronPythonDemo.py");//設定指令檔    ScriptScope scope = rbEng.CreateScope();     try    {     //設定參數     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、編譯運行可得計算結果(此處未做輸入的檢查)

以上就是C#調用Python指令碼的簡單方法,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.