前言
IronPython 是一種在 .NET 及 Mono上的 Python 實現,由微軟的 Jim Hugunin(同時也是 Jython 創造者) 所發起,是一個開源的項目,基於微軟的 DLR 引擎。在 2007 年,開發者決定改寫構架,使用動態類型系統以讓更多腳本語言能很容易地移植到NET Framework上。IronPython 的官方並未實現 Python 通用類庫,僅實現了部分核心類,社區的開源類庫實現有:
fepy(http://fepy.sourceforge.net/):fepy 為 IronPython 提供 Python 的大多數通用類庫的實現。
Test For IronPython
(1)在VS2017中新建窗體項目:IronPythonTest.
(2)VS菜單欄工具中打開“Nuget程序包管理器”:

(3)搜索IronPython程序包並安裝:

(4)安裝成功后,在exe程序所在文件夾下(也可以在其他目錄下,通過指定相對路徑),創建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:

(6)計算按鈕的點擊事件:
private void btnCalculate_Click(object sender, EventArgs e)
{
ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine rbEng = scriptRuntime.GetEngine("python");
ScriptSource source = rbEng.CreateScriptSourceFromFile("hello.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();
}
其中,我們需要使用的類型:
- ScriptEngine: 動態語言(IronPython)執行類,可於解析和執行動態語言代碼。
- ScriptScope:構建一個執行上下文,其中保存了環境及全局變量;宿主(Host)可以通過創建不同的 ScriptScope 來提供多個數據隔離的執行上下文。
- ScriptSource:操控動態語言代碼的類型,可以編譯(Compile)、運行(Execute)代碼。
可參考相關文章:
跨語言和跨編譯器的那些坑(CPython vs IronPython)
IronPython和C#交互(重點推薦)
