簡體   English   中英

默認安裝,Python中的“可選”依賴項(setuptools)

[英]Install by default, “optional” dependencies in Python (setuptools)

有沒有辦法為Python軟件包指定可選的依賴項, 默認情況下應該從pip 安裝,但如果無法安裝,安裝不應被視為失敗?

我知道我可以指定install_requires以便為使用可以輕松安裝某些可選依賴項的操作系統的90%用戶安裝軟件包,我也知道我可以指定extra_require來指定用戶可以聲明他們想要完全安裝到獲得這些功能,但我還沒有找到一種方法來進行默認的pip安裝嘗試安裝軟件包,但如果無法安裝則不要抱怨。

(我想要更新setuptoolssetup.py的特定包稱為music21 ,其中95%的工具可以在沒有matplotlib,IPython,scipy,pygame,一些模糊的音頻工具等的情況下運行但是包得到額外的安裝這些軟件包的能力和速度,我寧願讓人們默認擁有這些功能,但如果無法安裝則不報告錯誤)

無論如何都不是一個完美的解決方案,但你可以設置一個安裝后的腳本來嘗試安裝軟件包,如下所示:

from distutils.core import setup
from distutils import debug


from setuptools.command.install import install
class PostInstallExtrasInstaller(install):
    extras_install_by_default = ['matplotlib', 'nothing']

    @classmethod
    def pip_main(cls, *args, **kwargs):
        def pip_main(*args, **kwargs):
            raise Exception('No pip module found')
        try:
            from pip import main as pip_main
        except ImportError:
            from pip._internal import main as pip_main

        ret = pip_main(*args, **kwargs)
        if ret:
            raise Exception(f'Exitcode {ret}')
        return ret

    def run(self):
        for extra in self.extras_install_by_default:
            try:
                self.pip_main(['install', extra])
            except Exception as E:
                print(f'Optional package {extra} not installed: {E}')
            else:
                print(f"Optional package {extra} installed")
        return install.run(self)


setup(
    name='python-package-ignore-extra-dep-failures',
    version='0.1dev',
    packages=['somewhat',],
    license='Creative Commons Attribution-Noncommercial-Share Alike license',
    install_requires=['requests',],
    extras_require={
        'extras': PostInstallExtrasInstaller.extras_install_by_default,
    },
    cmdclass={
        'install': PostInstallExtrasInstaller,
    },
)

最簡單的方法是添加一個自定義安裝命令,該命令只需彈出以便安裝“可選”軟件包。 在你的setup.py

import sys
import subprocess
from setuptools import setup
from setuptools.command.install import install

class MyInstall(install):
    def run(self):
        subprocess.call([sys.executable, "-m", "pip", "install", "whatever"])
        install.run(self)

setup(
    ...

    cmdclass={
        'install': MyInstall,
    },
)

就像上面提到的hoefling一樣,這只有在您發布源代碼分發( .tar.gz.zip時才有效。 如果將包發布為構建的發行版( .whl ),它將無法工作。

這可能就是你要找的東西。 它似乎是設置工具的內置功能,允許您聲明“可選依賴項”。

https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies

防爆

setup(
    name="Project-A",
    ...
    extras_require={
        'PDF':  ["ReportLab>=1.2", "RXP"],
        'reST': ["docutils>=0.3"],
    }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM