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

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

 

转载于:https://www.cnblogs.com/xiamojinnian/p/5280526.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#调用Python程序可以通过以下步骤实现: 1. 首先,将Python程序转换为动态链接库(dll)。这可以通过使用Cython或者使用Python的ctypes库来实现。在转换为dll之前,确保已经安装了Python运行环境,并且安装了所需的第三方库(如numpy)\[1\]。 2. 在C#,使用DllImport特性来导入Python的dll文件。这样可以在C#调用Python的函数。确保在C#项目引用了Python的dll文件。 3. 在C#调用Python函数时,需要传递参数并接收返回值。可以使用C#的InteropServices命名空间的Marshal类来处理参数和返回值的转换。 下面是一个示例代码,演示了如何在C#调用Python程序: ```csharp using System; using System.Runtime.InteropServices; public class Program { \[DllImport("python_dll_path", CallingConvention = CallingConvention.Cdecl)\] public static extern double func(string a, string b); public static void Main(string\[\] args) { string a = "2"; string b = "3"; double result = func(a, b); Console.WriteLine(result); } } ``` 在上面的代码,`python_dll_path`是Python程序转换为的dll文件的路径。`func`是Python程序的函数名,通过DllImport特性导入。 请注意,这只是一个简单的示例,实际情况可能会更复杂。在实际使用,还需要处理异常、错误检查等情况。 希望这个回答对您有帮助!\[1\] #### 引用[.reference_title] - *1* [c#调用python的四种方法(尝试了四种,只详细讲解本人成功的后两种,其余方法只列出,详细用法请自行谷歌...](https://blog.csdn.net/qq_42063091/article/details/82418630)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [c#调用python的三种方法](https://blog.csdn.net/qq_36744449/article/details/116134794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值