简体   繁体   English

python swig 导入错误,如何解决?

[英]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:我在 python 中有一个代码,想用它来喝水,所以我在 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:并得到了一个名为 Olympics.py 的文件,我将那个文件复制到了我的项目中并写入了 import Olympics 但我遇到了一个错误,即 _Opympics.so 丢失了,所以我添加了它,但现在我得到了:

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...我不确定这是否可行,但我个人在使用 distutil 方面取得了更大的成功......

Make a setup.py python code.制作 setup.py python 代码。

# 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.然后 go 到您的终端, cd 到包含 Olympics 文件的目录。 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.生成.py和.so后,先检查python是否可以导入同目录下的模块。 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.如果成功,您应该可以将 Olympics.py 和 Olympics.so 移动到您要导入此模块的另一个目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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