简体   繁体   中英

python swig error importing, how to fix it?

I have a code in python and want to use swig with it, so I typed the following lines on linux:

1. swig -python Olympics.i
2. gcc -std=c99 -fPIC -c Olympics_wrap.c -I/usr/local/include/python3.6m
3. ld -shared Olympics.o Olympics_wrap.o -L/usr/local/include/python3.6m/ -o _Olympics.so

and got a file named Olympics.py, I copied only that one to my project and wrote import Olympics But I'm got an error that _Opympics.so is missing so I added it but now I'm getting:

Traceback (most recent call last):
  File "/../Olympics.py", line 1, in <module>
    import Olympics.py
  File "/../Olympics.py", line 26, in <module>
    _Olympics = swig_import_helper()
  File "/../Olympics.py", line 22, in swig_import_helper
    _mod = imp.load_module('_Olympics', fp, pathname, description)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: dlopen(../_Olympics.so, 2): no suitable image found.  Did find:
    ../_Olympics.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00
    ../_Olympics.so: stat() failed with errno=25

what I'm doing wrong?

This usually happens when it wasn't compiled/swigged correctly. I am not sure if this would work, but I personally had much more success with using distutil...

Make a setup.py python code.

# setup.py
from distutils.core import setup, Extension
module = Extension('_Olympics', sources['Olympics.c','Olympics.i'])
setup(name='Olympics', ext_modules=[module], py_modules=["Olympics"])

Then go to your terminal, cd to the directory that has Olympics files. Here, you can swig and compile it altogether in one line:

python setup.py build_ext --inplace

After it generates.py and.so, first check in python if you can import the module in the same directory. If it is successful, you should be able to move Olympics.py and Olympics.so to another directory where you want to import this module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM