当前位置:   article > 正文

c#嵌入Python代码_c# 嵌入python

c# 嵌入python

c# 用pythonnet 嵌入Python代码

C# 用pythonnet 嵌入Python代码,可以导入第三方库和自己python代码

我的测试环境

  • window10
  • conda 23.1.0(python3.10.9)
  • Microsoft Visual Studio Community 2022 (64 位) - Current版本 17.5.0

运行结果

请添加图片描述

步骤

  1. 安装python(或anaconda)
  2. 在VS项目NuGet中安装pythonnet
    • 工具->NuGet->管理…
  3. 创建python环境
    • 创建专用虚拟环境(windows下首先切换到要建立虚拟环境的根目录下),执行
    conda create --prefix=D:\condaenv\env_name python=3.10
    
    • 1
    路径及python版本根据需要自定义。
    • 使用Anaconda Prompt,激活虚拟环境
    conda activate F:\condaenv\env_name
    
    • 1
    • 安装Numpypip install numpy
  4. 如果为C#界面程序,需要配置为x64环境(与python吻合)
    • 鼠标放在VS项目上,右键属性->生成->常规->目标平台->选择x64
  5. 如果是自己的代码,需要放到建立虚拟环境包目录“{虚拟环境安装位置}\Lib\site-packages”中
  6. 代码示例
    • c#
    using Python.Runtime;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    string pathToVirtualEnv = "D:\\condaenv\\env_name";
    //string pathToVirtualEnv = "E:\\anaconda3";
    Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PYTHONPATH", $"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib;E:\\anaconda3\\Library\\bin;E:\\anaconda3\\Library\\usr\\bin;E:\\anaconda3\\Scripts", EnvironmentVariableTarget.Process);
    
    Runtime.PythonDLL = "D:\\condaenv\\env_name\\python310.dll";
    //Runtime.PythonDLL = "E:\\anaconda3\\python310.dll";
    PythonEngine.PythonHome = pathToVirtualEnv;
    PythonEngine.PythonPath = PythonEngine.PythonPath + ";" + Environment.GetEnvironmentVariable("PYTHONPATH", EnvironmentVariableTarget.Process);
    PythonEngine.Initialize();
    
    using (Py.GIL())
    {
        dynamic np = Py.Import("numpy");
        //dynamic np1 = Py.Import("test3");
        //Console.WriteLine(np1.Add(2));
        //Console.WriteLine(np.cos(np.pi * 2));
        //py.hello();
        double c = (double)(np.array(1));
        Console.WriteLine(c);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • winForm
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Python.Runtime;
    
    namespace DemoPythonnet
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            public dynamic np   = null;
            public dynamic a;
            public dynamic b;
            private void Form1_Load(object sender, EventArgs e)
            {
                string pathToVirtualEnv = "D:\\condaenv\\env_name";
                Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("PYTHONPATH", $"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib", EnvironmentVariableTarget.Process);
    
                Runtime.PythonDLL = "D:\\condaenv\\env_name\\python310.dll";
                PythonEngine.PythonHome = pathToVirtualEnv;
                PythonEngine.PythonPath = PythonEngine.PythonPath + ";" + Environment.GetEnvironmentVariable("PYTHONPATH", EnvironmentVariableTarget.Process);
                PythonEngine.Initialize();
                np = Py.Import("numpy");
            }
            private void button1_Click(object sender, EventArgs e)
            {
                //使用第三方库
                using (Py.GIL())
                {
                    Console.WriteLine(np.cos(np.pi * 2));
    
                    dynamic sin = np.sin;
                    Console.WriteLine(sin(5));
    
                    double c = (double)(np.cos(5) + sin(5));
                    Console.WriteLine(c);
    
                    a = np.array(new List<float> { 1, 2, 3 });
                    Console.WriteLine(a.dtype);
    
                    b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
                    Console.WriteLine(b.dtype);
    
                    Console.WriteLine(a * b);
                }
            }
            private void button2_Click(object sender, EventArgs e)
            {
                using (Py.GIL())
                {
                    Console.WriteLine(a * b);
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

感谢 https://blog.csdn.net/The_Moon_/article/details/127208124
感谢 https://blog.csdn.net/weixin_44064908/article/details/129270649

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/478445
推荐阅读
相关标签
  

闽ICP备14008679号