【发布时间】:2020-12-14 15:07:30
【问题描述】:
在 Python.NET 的官网上,它说它支持 Python 3.8。伟大的。 现在我有兴趣从用 C#(.NET 框架 v4.7.2)开发的应用程序调用我现有的 python 3.8 模块。
编辑:
由于 Python.NET 的作者几乎没有为来自 C# 的调用提供安装说明,因此我遵循了here 给出的说明。 请注意,我使用的是 miniconda3 和 python 32bit(我的项目需要后者),所以我做了以下操作:
-
在 VScode 中,我在“C:\ProgramData\Miniconda3\envs\py38_32”环境下安装了带有
pip install的pythonnet 以及所有必需的python 包(我们在这里使用numpy作为示例) . -
在 C# 中设置环境路径(在 VS2019 中):
string pythonPath1 = @"C:\ProgramData\Miniconda3\envs\py38_32";
string pythonPath2 = @"C:\ProgramData\Miniconda3\envs\py38_32\Lib\site-packages";
Environment.SetEnvironmentVariable("PATH", pythonPath1, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath1, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath2, EnvironmentVariableTarget.Process);
-
从我的项目中的“py38_32\Lib\site-packages”文件夹中引用了Python.Runtime.dll并添加了
using Python.Runtime; -
尝试导入numpy:
using (Py.GIL()) { dynamic np = Py.Import("numpy"); //fail on this line with ImportError }
numpy 导入失败,出现“Python.Runtime.PythonException: 'ImportError”。它还说“Python版本是:来自“\bin\Debug\MyProject.exe”的Python3.8 ...似乎它在我的调试文件夹中寻找python,而不是在上面提到的路径中......也许...... . 并且使用相同的环境从 VScode 导入 numpy 完全正常。
有人知道这里发生了什么吗?
【问题讨论】:
标签: python c# python.net