zoukankan      html  css  js  c++  java
  • 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); }

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

  • 相关阅读:
    Nodejs接收图片base64格式保存为文件
    tracking.js实现前端人脸识别
    node.js执行shell命令进行服务器重启
    Cordova 实现沉浸式(透明)状态栏效果
    SpringBoot启动原理详解
    连续子数组的最大乘积及连续子数组的最大和(Java)
    记录面试遇到的几个自己不太熟悉的问题(3)
    记录面试遇到的几个自己不太熟悉的问题(2)
    记录面试遇到的几个自己不太熟悉的问题(1)
    Java设计模式
  • 原文地址:https://www.cnblogs.com/xiamojinnian/p/5280526.html
Copyright © 2011-2022 走看看