最近因為項目設計,有部分使用Python腳本,因此代碼中需要調用python方法。
1.首先,在c#中調用python必須安裝IronPython,在 http://ironpython.codeplex.com/ 中下載
2.對應用程序添加IronPython.dll和Microsoft.Scripting.dll 的引用

3.調用python:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IronPython.Hosting; using Microsoft.Scripting.Hosting; namespace WpfUsingPythonDemo { public class UsingPython { private ScriptRuntime pyRuntime = null; private dynamic obj = null; public UsingPython() { string serverpath = AppDomain.CurrentDomain.BaseDirectory + "frs_main.py";//所引用python路徑 pyRuntime = Python.CreateRuntime(); ScriptEngine Engine = pyRuntime.GetEngine("python"); ScriptScope pyScope = Engine.CreateScope(); //Python.ImportModule(Engine, "random"); obj = Engine.ExecuteFile(serverpath, pyScope); } public bool ExcutePython() { try { if (null != obj) { obj.frs_init();//調用frs_main.py中的方法 } else { return false; } return true; } catch(Exception ex) { throw ex; } } } }
4.c#中引用的python應該是IronPython,與CPython版本和模塊中有差別,所以需要注意使用版本
5.因為所使用的python文件中引用了很多模塊,所以運行時會找不到python庫,在網上查了一下,需要引入搜索路徑並且引入庫,如下:
public UsingPython()
{
string serverpath = AppDomain.CurrentDomain.BaseDirectory + "frs_main.py";//所引用python路徑
pyRuntime = Python.CreateRuntime();
ScriptEngine Engine = pyRuntime.GetEngine("python");
//手動設置搜索路徑
ICollection<string> Paths = Engine.GetSearchPaths();
Paths.Add("//Lib");
Paths.Add("//Lib//site-packages");
Paths.Add(AppDomain.CurrentDomain.BaseDirectory + "frs");
//importpy文件中的庫,需要注意先后引用順序
Engine.ImportModule("sys");
Engine.ImportModule("logging");
Engine.ImportModule("Queue");
Engine.ImportModule("ctypes");
Engine.ImportModule("json");
Engine.ImportModule("os");
ScriptScope pyScope = Engine.CreateScope(); //Python.ImportModule(Engine, "random");
obj = Engine.ExecuteFile(serverpath, pyScope);
}
這是自己摸索找到的解決方案,希望以后可以有更好的方法。
