从 C# 调用 Python(错误:Runtime.PythonDLL 未设置或未指向受支持的 Python 运行时 DLL)

问题描述 投票:0回答:1

这是我的代码:

using Python.Runtime;
using System;

class Program
{
    static void Main()
    {
        try
        {
            // Set Python home and DLL paths
            PythonEngine.PythonHome = @"C:\Users\toto\AppData\Local\Programs\Python\Python311";
            Runtime.PythonDLL = @"C:\Users\toto\AppData\Local\Programs\Python\Python311\python311.dll";

            // Initialize the Python engine
            PythonEngine.Initialize();

            using (Py.GIL())
            {
                // Import and use Python modules
                dynamic sys = Py.Import("sys");
                Console.WriteLine($"Python version: {sys.version}");
            }

            // Shutdown the Python engine
            PythonEngine.Shutdown();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

我正在打印此控制台

Error: Runtime.PythonDLL was not set or does not point to a supported Python runtime DLL. See https://github.com/pythonnet/pythonnet#embedding-python-in-net

C:\Users\toto\Desktop\C# Python\ConsoleApp1\ConsoleApp1\bin\Debug\net6.0\ConsoleApp1.exe (process 6368) exited with code 0 (0x0).

我尝试过的事情:我尝试了从 8 到 12 的不同 Python 版本,我将 Target 框架从 8 降级到 6,但仍然没有成功。我该如何解决这个问题?我查看了类似的主题,但他们的解决方案对我不起作用,请帮忙

编辑:我的平台目标是x64

Microsoft Windows [Version 10.0.18363.418]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\toto>python -c "import platform; print(platform.architecture()[0])"
64bit

C:\Users\toto>where python
C:\Users\toto\AppData\Local\Programs\Python\Python311\python.exe
C:\Users\toto\AppData\Local\Microsoft\WindowsApps\python.exe

C:\Users\toto>
python c# python.net
1个回答
0
投票

我删除了“PythonEngine.PythonHome = @”C:\Users oto\AppData\Local\Programs\Python\Python310”;”它起作用了。

using Python.Runtime;
using System;

class Program
{
    static void Main()
    {
        try
        {
            // Set Python home and DLL paths
            //PythonEngine.PythonHome = @"C:\Users\toto\AppData\Local\Programs\Python\Python310";
            Runtime.PythonDLL = @"C:\Users\toto\AppData\Local\Programs\Python\Python310\python310.dll";

            // Initialize the Python engine
            PythonEngine.Initialize();

            using (Py.GIL())
            {
                // Import and use Python modules
                dynamic sys = Py.Import("sys");
                Console.WriteLine($"Python version: {sys.version}");
            }

            // Shutdown the Python engine
            PythonEngine.Shutdown();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.