簡體   English   中英

setup.py中的條件要求

[英]Conditional requirements in setup.py

我正在編寫一個依賴於file-magic ,該大多數平台上都可以正常運行,但是在Alpine Linux中,file-magic無法正常工作,因此我需要改用python-magic庫。

現在,我知道如何編寫自己的代碼來處理不同的Python庫API,但是我不知道該怎么做,就是根據我們所使用的系統編寫setup.cfgsetup.py以具有不同的要求正在安裝。

我認為最好的選擇是使用PEP 508規則,但是我無法弄清楚如何說“像Alpine這樣的libmagic”或這種語法,更不用說在包的setup.py中可以使用了。 確實,如果不安裝file-magic並看着它消失,我什至無法弄清楚如何分辨這些體系結構之間的區別:-(

當然,這種事情一定有最佳實踐嗎?

更新

在從下面的Tim那里獲得了更廣泛的理解之后,我整理了這個技巧以使其正常工作:

def get_requirements():
    """
    Alpine is problematic in how it doesn't play nice with file-magic -- a
    module that appears to be the standard for most other Linux distros.  As a
    work-around for this, we swap out file-magic for python-magic in the Alpine
    case.
    """

    config = configparser.ConfigParser()
    config.read("setup.cfg")
    requirements = config["options"]["install_requires"].split()

    os_id = None
    try:
        with open("/etc/os-release") as f:
            os_id = [_ for _ in f.readlines() if _.startswith("ID=")][0] \
                .strip() \
                .replace("ID=", "")
    except (FileNotFoundError, OSError, IndexError):
        pass

    if os_id == "alpine":
        requirements[1] = "python-magic>=0.4.15"

    return requirements


setuptools.setup(install_requires=get_requirements())

這允許使用setup.cfg的聲明性語法,但是如果安裝目標是Alpine系統,則可以調整install_requires值。

您可能要使用平台模塊來嘗試識別系統詳細信息。

最好的選擇是嘗試使用platform.architecture()platform.platform()platform.system()的組合,並進行適當的錯誤處理並考慮所有可能的返回信息。

例:

我在Win10上運行,這是這些函數的輸出(以及更多):

>>> import platform
>>> print(platform.architecture())
('32bit', 'WindowsPE')
>>> print(platform.platform())
Windows-10-10.0.17134-SP0
>>> print(platform.processor())
Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
>>> print(platform.system())
Windows

編輯

上面的答案不一定返回您想要的信息(我沒有提到平台模塊中所有不推薦使用的功能)。

深入研究,將得出此SO結果 ,這說明已棄用了用於收集發行名稱的內置平台功能。

官方文檔指向名為distro的PyPi軟件包的方向。 PyPi上的發行文檔承認需要這種類型的信息,並且在其中找到的示例用法如下所示:

>>> import distro
>>> distro.linux_distribution(full_distribution_name=False)
('centos', '7.1.1503', 'Core')

暫無
暫無

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

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