在 IronPython 中导入外部模块 [英] Importing external module in IronPython
问题描述
我目前正在开发一个用 C# 编写的应用程序,我将 IronPython 嵌入其中.我通常对此没有问题,但有一件事情我不知道如何处理.
I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with.
我想将外部模块导入脚本.我怎样才能做到这一点?简单的 import ext_lib
不起作用.我应该将 lib 路径添加到 sys.path
吗?也许可以将 lib 的 .py 文件复制到 app 目录并从那里导入?
I want to import an external module into the script. How can I do that? Simple import ext_lib
doesn't work. Should I add a path to the lib to sys.path
?
Maybe it is possible to copy the lib's .py file into app directory and import from there?
我最终选择了另一个解决方案 - 使用 py2exe
编译我的脚本,我只是从主 C# 应用程序使用 Process
(不使用 IronPython)运行它.
I finally chosen another solution - compiled my script with py2exe
and I'm just running it from main C# app with Process
(without using IronPython).
无论如何,谢谢你的帮助;)
Anyway, thanks for help ;)
推荐答案
在使用 PythonEngine 编译脚本之前,我将脚本的目录添加到引擎的搜索路径中.这是我在 C# 代码中所做的:
Before compiling a script with the PythonEngine, I add the script's directory to the engine's search path. This is what I do in the C# code:
string dir = Path.GetDirectoryName(scriptPath);
ICollection<string> paths = engine.GetSearchPaths();
if (!String.IsNullOrWhitespace(dir))
{
paths.Add(dir);
}
else
{
paths.Add(Environment.CurrentDirectory);
}
engine.SetSearchPaths(paths);
现在,如果库位于您正在执行的脚本所在的目录中,它们将是可导入的.
Now if the libraries are in the directory where the scripts, which you are executing, reside they will be importable.
这篇关于在 IronPython 中导入外部模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!