Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Python Module through C# .NET using IronPython

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?

like image 709
ToOsIK Avatar asked Oct 04 '12 20:10

ToOsIK


People also ask

How do I access a module written in Python from C?

You need include Python. h header file in your C source file, which gives you access to the internal Python API used to hook your module into the interpreter. Make sure to include Python. h before any other headers you might need.

Can I mix Python with C?

Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

Can you write a Python library in C?

To write Python modules in C, you'll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code. All of these tools and more are collectively bundled in the Python.


1 Answers

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";
like image 183
Constantine Avatar answered Sep 28 '22 23:09

Constantine