C#中調用python方法


最近因為項目設計,有部分使用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;
           }
        }
    }
}
Using Python

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

  這是自己摸索找到的解決方案,希望以后可以有更好的方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM