V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
secsilm
V2EX  ›  Python

Python 打包成 SO 文件

  •  
  •   secsilm ·
    secsilm · 2018-12-06 14:53:09 +08:00 · 4619 次点击
    这是一个创建于 1960 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在需要将 Python 源码打包成 SO 文件,然后给再用 Python 调用这个生成的 SO 文件。

    我查了一些资料,例如 https://www.cnblogs.com/ke10/p/py2so.html,然后照着生成了 SO 文件,接着在使用 ctypes 调用的时候出了问题,报错 AttributeError: build/lib.linux-x86_64-3.6/test.cpython-36m-x86_64-linux-gnu.so: undefined symbol: np_add

    test.py 文件:

    import numpy as np
    
    def np_add(x, y):
        return x + y
    
    if __name__ == "__main__":
        x = 1
        y = 2
        print(f"{x} + {y} = {np_add(x, y)}")
    

    setup.py 文件:

    from distutils.core import setup
    from Cython.Build import cythonize
    
    setup(ext_modules=cythonize("test.py"))
    

    各位有什么建议吗?或者说不采取这种方法,有其他经过试验的方法可以成功打包并成功调用的吗?

    希望过来人给点建议,先谢谢了。

    3 条回复    2018-12-06 17:18:02 +08:00
    holajamc
        1
    holajamc  
       2018-12-06 16:49:46 +08:00
    http://nuitka.net/
    试试这个~
    anonymous256
        2
    anonymous256  
       2018-12-06 17:00:59 +08:00
    我在 win 下是编译成功的, 你的环境里可能没有安装 swig. which swig 你检查一下

    而且似乎你写了一条没有用的语句: if __name__ == "__main__" ,,这是无效的, 既然已经用了 cython, 则不存在 main 的入口.
    anonymous256
        3
    anonymous256  
       2018-12-06 17:18:02 +08:00 via Android
    我没有使用你的 setup.py ,你修改下试试。
    from distutils.core import setup, Extension
    import numpy

    np = Extension('test', sources=['test.py'],
    include_dirs=[numpy.get_include()])
    setup(ext_modules=[np])
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3342 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:38 · PVG 08:38 · LAX 17:38 · JFK 20:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.