Python.Net如何执行包中模块?导入问题求助
Python.NET 模块导入问题
我的文件夹结构如下:
C:\Test\System\ C:\Test\System\intercepts\ C:\Test\System\intercepts\utils1\ C:\Test\System\intercepts\utils2\
后三个文件夹都包含空的__init__.py文件,utils1和utils2文件夹内有多个.py模块。我想要执行utils1文件夹中general.py模块内的startup函数。
C:\Test\System下的entry.py文件导入了各子文件夹的模块:
from intercepts.utils1 import general from intercepts.utils1 import foobar from intercepts.utils2 import ... ..etc..
初始C#代码与错误
我用以下C#代码尝试执行该模块并调用startup函数:
const string EntryModule = @"C:\Test\System\entry.py"; using (Py.GIL()) { using (var scope = Py.CreateScope()) { var code = File.ReadAllText(EntryModule); var scriptCompiled = PythonEngine.Compile(code, EntryModule); scope.Execute(scriptCompiled); dynamic func = scope.Get("general.startup"); func(); } }
但在scope.Execute(...)处触发PythonException,提示:
No module named 'intercepts' File "C:\Test\System\entry.py", line 1, in <module> from intercepts.utils1 import general
我曾用IronPython(Python 2.7)完成等效操作,所以认为是Python.Net的使用问题,当前使用pythonnet 3.0.0 NuGet包。
调整后的尝试与新错误
我尝试改用以下方式导入entry.py:
dynamic os = Py.Import("os"); dynamic sys = Py.Import("sys"); sys.path.append(os.path.dirname(EntryModule)); Py.Import(Path.GetFileNameWithoutExtension(EntryModule));
现在问题发生变化:entry.py中先导入general模块,再导入foobar模块,而foobar.py中有import general语句。运行C#代码时出现新错误:
No module named 'general' File "C:\Test\System\intercepts\utils1\foobar.py", line 1, in <module> import general File "C:\Test\System\entry.py", line 2, in <module> from intercepts.utils1 import foobar
疑问
- 为何foobar模块无法识别之前导入的general模块?
- 使用
Py.Import()解决原问题的思路是否正确?
内容的提问来源于stack exchange,提问作者Andrew Stephens
相关产品推荐
相关产品推荐

