Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import python module from .so file?

[me@hostname python]$ cat hello_world.cc #include <string> #include <Python.h> #include <boost/python.hpp>  namespace {   std::string greet() { return "Helloworld"; } }  using namespace boost::python;  BOOST_PYTHON_MODULE(hello_world) {   def("greet",greet); }  [me@hostnmae python]$ g++ -c -fPIC hello_world.cc -I/path/to/boost/headers -I/path/to/python/headers -o hello_world.o [me@hostname python]$ g++ -shared -Wl,-soname,libhello_world.so -o libhello_world.so  hello_world.o [me@hostname python]$ python Python 2.7.1 (r271:86832, Jan 10 2011, 09:46:57) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.append('.') >>> import hello_world Traceback (most recent call last):   File "<stdin>", line 1, in <module> ImportError: No module named hello_world >>> 

I created the .so file as shown above but I'm not able to import inside python. what am I missing?

like image 347
balki Avatar asked Jun 10 '12 11:06

balki


People also ask

How do I run a .so file in Python?

If the . so file exposes a PyInit_<module_name> function, its path (or parent directory's path) can be added to the environment variable PYTHONPATH . Then you can import the module via import <module_name> .

What is Python .so file?

The basics of using a Shared Library file A file with the . SO file extension is a Shared Library file. They contain information that can be used by one or more programs to offload resources so that the application(s) calling the SO file doesn't have to actually provide the file.

What does __ init __ PY do in Python?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.


2 Answers

take that 'hello_world.so' file and and make new python file (in the same dir) named as 'hello_world.py'. Put the below code in it.. .

def __bootstrap__():    global __bootstrap__, __loader__, __file__    import sys, pkg_resources, imp    __file__ = pkg_resources.resource_filename(__name__,'hello_world.so')    __loader__ = None; del __bootstrap__, __loader__    imp.load_dynamic(__name__,__file__) __bootstrap__() 

now you can import this hello_world as:

>>> import hello_world 
like image 96
namit Avatar answered Oct 05 '22 18:10

namit


It must be called hello_world.so, not libhello_world.so.

like image 33
Cat Plus Plus Avatar answered Oct 05 '22 18:10

Cat Plus Plus