1

我正在编写一个依赖于file-magic的,它适用于大多数平台,但在 Alpine Linux 中,file-magic 不起作用,所以我需要改用python-magic库。

现在我知道如何编写自己的代码来处理不同的 Python 库 API,但我不知道如何编写自己的代码setup.cfgsetup.py根据我们正在安装的系统有不同的要求。

我认为最好的选择是使用PEP 508规则,但我不知道如何说“libmagic like Alpine”或该语法中的内容,更不用说这是否可以在包的 setup.py 中使用。确实,我什至无法弄清楚如何在不安装file-magic和看着它死掉的情况下分辨架构之间的区别:-(

当然,这种事情必须有最佳实践吗?

更新

在下面蒂姆的一些更广泛的理解之后,我拼凑了这个黑客来让它工作:

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,但install_requires如果安装目标是 Alpine 系统,则会调整值。

4

1 回答 1

1

您可能想使用平台模块来尝试识别系统详细信息。

最好的办法是尝试使用 、 和 的组合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')
于 2019-02-11T18:40:56.567 回答