简体   繁体   English

为python包制作可选C扩展的最简单方法是什么?

[英]What is the easiest way to make an optional C extension for a python package?

I've created a C extension that I'd like to enable in my Python package (using setuptools) only if a command line option is passed in. What is the easiest way to do this? 我已经创建了一个C扩展,我想在我的Python包中启用(使用setuptools),只有传入命令行选项。最简单的方法是什么?

I can't seem to find any straightforward ways of going about this. 我似乎无法找到任何直截了当的方式来解决这个问题。

There's actually a distribute/setuptools feature called "Features" that can be used for this. 实际上有一个名为“Features”的分发/设置工具功能可以用于此目的。 It's explicitly designed to have setup.py do different things based on --with-xxx and --without-xxx command line options. 它明确地设计为让setup.py根据--with-xxx--without-xxx命令行选项执行不同的操作。

  • This blog post gives a nice introduction, I can't find any better documentation at this time (besides the Distribute source - the Feature class and features keyword ). 这篇博文给出了一个很好的介绍,我目前找不到任何更好的文档(除了Distribute源 - Feature类features关键字 )。
  • The jinja project's setup.py uses Features for your exact purpose, it might be a good template to work from. jinja项目的setup.py使用功能用于您的确切目的,它可能是一个很好的模板。
  • The simplejson setup.py also does something similar, except that it's coded to always try to build the C-extension feature it defines, and fall back gracefully to pure-python when building fails; simplejson setup.py也做了类似的事情,除了它被编码为总是尝试构建它定义的C扩展功能,并在构建失败时优雅地回退到pure-python; this may also be useful for your purpose. 这也可能对您有用。
ext_modules = []
if '--add-this' in sys.argv:
    ext_modules.append(Extension(...))
    sys.argv.remove('--add-this')
setup(...
      ext_modules = ext_modules
)

This is hacky, but might be easiest. 这很hacky,但可能最容易。 A more advanced approach would be to extend the Distribution class to support a flag, say --with-modules and then customize ext_modules inside finalize_options. 更高级的方法是扩展Distribution类以支持标志,比如--with-modules ,然后在finalize_options中自定义ext_modules。

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

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