Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 调用python

作者:风皇霸陵   发布日期:2026-04-14   浏览:87

using System;
using Python.Runtime;

class Program
{
    static void Main(string[] args)
    {
        // 初始化Python运行时环境
        PythonEngine.Initialize();
        using (Py.GIL())
        {
            // 导入Python模块
            dynamic np = Py.Import("numpy");
            Console.WriteLine(np.cos(np.pi * 2));

            // 调用Python函数
            dynamic sin = np.sin;
            Console.WriteLine(sin(5));

            double c = np.cos(5) ** 2 + np.sin(5) ** 2;
            Console.WriteLine(c);

            // 定义并调用Python代码块
            string pythonCode = @"
def greet(name):
    return 'Hello, ' + name
";
            dynamic pyGlobals = Py.Dict();
            Py.RunString(pythonCode, pyGlobals);
            dynamic greet = pyGlobals["greet"];
            Console.WriteLine(greet("World"));

            // 清理Python运行时环境
            PythonEngine.Shutdown();
        }
    }
}

解释说明

  1. 初始化Python运行时环境:

    • 使用 PythonEngine.Initialize() 来初始化Python运行时环境。
  2. 导入Python模块:

    • 使用 Py.Import("numpy") 导入Python的 numpy 模块,并将其赋值给一个动态类型变量 np,以便后续使用。
  3. 调用Python函数:

    • 使用 np.sinnp.cos 调用Python中的 sincos 函数,并打印结果。
  4. 定义并调用Python代码块:

    • 使用 Py.RunString 执行一段包含Python函数定义的字符串,并通过 pyGlobals 获取该函数,然后调用它。
  5. 清理Python运行时环境:

    • 使用 PythonEngine.Shutdown() 清理Python运行时环境,确保资源释放。

这个示例展示了如何在C#中使用 Python.Runtime 库来调用Python代码。你需要确保已经安装了 Python.Runtime 库,并且你的环境中已经正确配置了Python解释器。

上一篇:c#调用python

下一篇:c#调用python脚本

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站