c# - Unity3D:(Python.net)PythonException:ModuleNotFoundError
问题描述
我正在尝试从 Unity3d 中的 c# 文件中调用 python 类。Numpy 和 os 模块工作正常。
void Start()
{
startTime = Time.time;
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
UnityEngine.Debug.Log(np.cos(np.pi * 2));
dynamic sin = np.sin;
UnityEngine.Debug.Log(sin(5));
double c = np.cos(5) + sin(5);
UnityEngine.Debug.Log(c);
dynamic a = np.array(new List<float> { 1, 2, 3 });
UnityEngine.Debug.Log(a.dtype);
dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
UnityEngine.Debug.Log(b.dtype);
UnityEngine.Debug.Log(a * b);
dynamic os = Py.Import("os");
UnityEngine.Debug.Log(os.getcwd());
dynamic test = Py.Import("clrTest"); // this throws me an error
}
}
clrTest 是我的自定义类clrTest.py
class clsMyTest:
"""clsTest.clsMyTest class"""
@staticmethod
def Test03():
return 42
def Test04():
return 42
def Test01():
return 42
@staticmethod
def Test02():
return 42
我收到以下错误
PythonException: ModuleNotFoundError : No module named 'clrTest'
Python.Runtime.Runtime.CheckExceptionOccurred () (at <38fa310f96774b388b3fb5f7d3ed5afc>:0)
Python.Runtime.PythonEngine.ImportModule (System.String name) (at <38fa310f96774b388b3fb5f7d3ed5afc>:0)
Python.Runtime.Py.Import (System.String name) (at <38fa310f96774b388b3fb5f7d3ed5afc>:0)
我尝试将我的 python 文件放在与 c# 文件相同的目录中,在根目录和插件文件夹中。我仍然收到此错误。该怎么办?
解决方案
Pythonnet 的 Py.Import() 行为与 Python "import" 语句相同。要成功导入模块,该模块必须位于 Python 解释器搜索路径的位置之一。解释器搜索路径是特定于平台的,可以修改。有关详细信息,请参阅 Python 文档: 修改 Python 的搜索路径。
在 Windows 下,我通常采用以下两个选项之一:
修改托管进程的 PYTHONPATH 环境变量:
Environment.SetEnvironmentVariable("PYTHONPATH", @"D:\MyPythonModules\", EnvironmentVariableTarget.Process);
通过使用 pythonnet 执行 python 代码字符串来修改 Python 的 sys.path :
using (Py.GIL()) { int returnValue = PythonEngine.RunSimpleString("import sys;sys.path.insert(1, 'D:/MyPythonModules/');"); if (returnValue != 0) { //throw exception or other failure handling } }
与 Python 文档中列出的其他选项相比,使用这些选项的优势在于您无需修改 Python 安装。第二个选项也适用于忽略环境变量的嵌入式 Python 。仅针对特定进程修改 PYTHONPATH 的优点是您不会影响系统中的其他进程。但是,如果你只需要快速测试一些东西,你可以直接修改系统的 PYTHONPATH 环境变量。
推荐阅读
- reactjs - 为什么高阶组件的语法经常采用高阶函数形式?而不是额外的论点?
- delphi - 有没有人将 IBX (Interbase Express) TClientDataSet -> TDatasetProvider -> TIBQuery 转换为 FireDAC?
- java - ORA-00905: missing keyword in case statement
- visual-studio-code - 使用 Mac 在 VS 上创建新项目
- sql - 为什么 postgreSQL INSERT 语句中复合类型的语法不同,并且取决于数据类型是命名还是未命名的事实?
- batch-processing - 在批处理脚本中过滤字符串中的单词
- android - Android ConstraintLayout 移动微调器的位置
- angular - 如何检索分组在 forkJoin 中的多个可观察对象的报告进度?
- java - Java Asm wrap new 特定类初始化实例
- amazon-web-services - SageMaker 端点部署尝试查找依赖文件时一直失败