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
guyskk0x0
V2EX  ›  Python

请问有什么方式能把 Cython 代码编译为纯 Python 代码?

  •  
  •   guyskk0x0 ·
    guyskk · 2019-11-15 16:10:05 +08:00 · 3391 次点击
    这是一个创建于 1621 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有一个库使用 Cython 编写,以提高执行速度,但很多场景安装 gcc 等编译工具很麻烦,所以想同时提供一个纯 Python 的版本,而我又不想类似的代码写两套。

    有什么办法能把 .pyx 文件中的静态类型声明等等去掉,变成纯 Python 代码?

    8 条回复    2019-11-16 21:17:37 +08:00
    monsterxx03
        1
    monsterxx03  
       2019-11-15 16:12:59 +08:00   ❤️ 1
    应该打个 wheel 格式的包, 其他地方安装的时候就不用编译了: https://pythonwheels.com/
    guyskk0x0
        2
    guyskk0x0  
    OP
       2019-11-15 17:00:02 +08:00
    @monsterxx03 wheel 包需要在 windows, mac, linux 上分别打包,也是很麻烦
    superrichman
        3
    superrichman  
       2019-11-15 17:17:00 +08:00 via iPhone
    也许可以考虑扔到 docker 里去?
    ethego
        4
    ethego  
       2019-11-15 17:32:11 +08:00
    当然要分别打包,cython 写的玩意是编译到 c 再进一步编译到 binary 的,没有可以编译到 python 的方法。如果要分发二进制,就需要按系统分别打包。
    ethego
        5
    ethego  
       2019-11-15 17:32:47 +08:00
    不可以,你可以在手写一个纯 python 的版本。
    wangyzj
        6
    wangyzj  
       2019-11-15 18:05:00 +08:00
    pyinstaller
    hakono
        7
    hakono  
       2019-11-15 18:29:36 +08:00 via iPhone   ❤️ 1
    别瞎想,照着你的 c 代码再写个 python 实现更快
    guyskk0x0
        8
    guyskk0x0  
    OP
       2019-11-16 21:17:37 +08:00
    @ethego #4
    @hakono #7
    我暂时用正则和字符串替换实现了 .pyx 转 .py ,实现很不优雅,靠单元测试保证转换后功能正确。
    https://github.com/guyskk/validr/pull/30/files#diff-fcbabf283e1a432f9d3830f80cd5bdd3
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5366 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 07:19 · PVG 15:19 · LAX 00:19 · JFK 03:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.