C#中調用python方法

最近由於項目設計,有部分使用Python腳本,所以代碼中須要調用python方法。python

1.首先,在c#中調用python必須安裝IronPython,在  http://ironpython.codeplex.com/  中下載json

2.對應用程序添加IronPython.dll和Microsoft.Scripting.dll 的引用c#

 

3.調用python:dom

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;
           }
        }
    }
}
Using Python

4.c#中引用的python應該是IronPython,與CPython版本和模塊中有差異,因此須要注意使用版本ide

5.由於所使用的python文件中引用了不少模塊,因此運行時會找不到python庫,在網上查了一下,須要引入搜索路徑而且引入庫,以下:spa

 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); }

  這是本身摸索找到的解決方案,但願之後能夠有更好的方法。設計

相關文章
相關標籤/搜索