IronPython无法导入模块"os"。

6

我的C#代码:

//Create the ScriptRuntime
engine = Python.CreateEngine();
//Create the scope for the ScriptEngine
scope = engine.CreateScope();


string pyfile = "D:\\MyAddin\\test.py";
ScriptSource source = engine.CreateScriptSourceFromFile(pyfile);
var rt = source.Execute(scope);

还有我的test.py文件:

import os
import sys
...
print("test")
...

我在构建时没有问题,但在运行时VS给我一个错误“无法导入模块" os"”。出错的原因是什么?
1个回答

7
当在你的代码中托管IronPython时,你需要将库添加到路径中。并非所有库都会默认包含。
你可以通过引擎来添加它:
var engine = Python.CreateEngine();
var paths = engine.GetSearchPaths();
paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
//paths.Add(@"C:\Python27\Lib"); // or you can add the CPython libs instead
engine.SetSearchPaths(paths);

或通过您的脚本:

import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os

但是Python脚本将被安装在Python路径中,而不是IronPython安装路径中,对吗? - Pyd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接