Import Python Module through C# .NET using IronPython

对着背影说爱祢 提交于 2019-12-01 18:07:23

问题


I am trying to run a Python class through C# .NET using IronPython, a couple of the Modules imported by the Python class are:

import collections
import nltk.classify.util

In order to import these when running IronPython, I am using the GetSearchPath collection of the ScriptEngine to add the path to the location of the Python library, as such:

ICollection<string> paths = pyEngine.GetSearchPaths();
string dir = @"C:\Python27\Lib\";
paths.Add(dir);
string dir2 = @"C:\Python27\Lib\site-packages\nltk\classify\";
paths.Add(dir2);
pyEngine.SetSearchPaths(paths);

This seems to run fine for the collections Module, but not the nltk.classify.util, and I get the following error when calling the Execute method of the ScriptEngine:

No module named nltk.classify.util

Even tho the util module lives in the path specified above. I take it the issue has to do with the way the import is specified in the Python class ('.' delimited), just not sure how to solve it. Any ideas where am going wrong?


回答1:


Python uses the structure of a package name to search for a module, so if you ask for nltk.classify.util it will look for nltk\classify\util.py starting from each directory in the search path.

So in your example, you want to change dir2 as follows:

string dir2 = @"C:\Python27\Lib\site-packages";


来源:https://stackoverflow.com/questions/12735642/import-python-module-through-c-sharp-net-using-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!