本文介绍了我可以在 setuptools 中定义可选包吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的一个包需要一个 JSON 解析器/编码器,并且被设计为使用 simplejson 如果可用的话回退到 json 模块(在标准库中)如果必要的(因为基准测试显示 simplejson 更快).

Currently one of my packages requires a JSON parser/encoder, and is designed to use simplejson if available falling back to the json module (in the standard library) if necessary (as benchmarks show simplejson is faster).

然而,最近它受到了打击&不知道在使用 zc.buildout 时是否会安装 simplejson - 我相信随着迁移到 github 的一些事情.这让我想知道;是否可以在我的 setup.py 文件中定义可选包,如果不可用,不会停止我的包的安装?

However, recently it's been hit & miss as to whether simplejson will install when using zc.buildout - something with the move to github, I believe. Which got me wondering; is it possible to define optional packages in my setup.py file which, if unavailable, won't stop the installation of my package?

推荐答案

安装时的可选包.

我假设您在谈论您的 setup.py 脚本.您可以将其更改为:

optional packages at installation time.

I am assuming you are talking about your setup.py script.You could change it to have:

# mypackage/setup.py

extras = {
   'with_simplejson': ['simplejson>=3.5.3']
}

setup(
    ...
    extras_require=extras,
    ...)

那么您可以执行以下任一操作:

then you can do either of:

  • pip install mypackage,
  • pip install mypackage[with_simplejson]

后者安装simplejson>=3.5.3.

与其尝试安装所有内容并回退到已知好的版本,您可能想要安装您知道工作的软件包子集.

Instead of trying to install everything and fallback to a known good version,you would want to install the subset of packages you know work.

一旦您可以安装两组不同的软件包,您需要以确保您可以使用它们(如果它们可用).例如.为您的 json 导入:

Once you have two different sets of packages that could be installed, you needto make sure you can use them if they are available. E.g. for your json import:

try:
    # helpful comment saying this should be faster.
    import simplejson as json
except ImportError:
    import json

另一个更复杂的例子:

try:
    # xml is dangerous
    from defusedxml.cElementTree import parse
except ImportError:
    try:
        # cElementTree is not available in older python
        from xml.cElementTree import parse
    except ImportError:
        from xml.ElementTree import parse

但是你也可以在一些包中找到这种模式:

But you can also find this pattern in some packages:

try:
    optional_package = None
    import optional.package as optional_package
except ImportError:
    pass

...

if optional_package:
    # do addtional behavior

这篇关于我可以在 setuptools 中定义可选包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:26