-
C#調用Python腳本的簡單示例
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、編譯運行可得計算結果(此處未做輸入的檢查)
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
