IronPython无法导入模块"os"

ric*_*ich 4 .net ironpython

我的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);
Run Code Online (Sandbox Code Playgroud)

和我的test.py:

import os
import sys
...
print("test")
...
Run Code Online (Sandbox Code Playgroud)

我在构建时没有问题,但在运行时VS给我一个错误"无法导入模块"os"".错误在哪里?

Jef*_*ado 6

在代码中托管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);
Run Code Online (Sandbox Code Playgroud)

或者通过你的脚本:

import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
Run Code Online (Sandbox Code Playgroud)