我正在编写一个依赖于file-magic的库,它适用于大多数平台,但在 Alpine Linux 中,file-magic 不起作用,所以我需要改用python-magic库。
现在我知道如何编写自己的代码来处理不同的 Python 库 API,但我不知道如何编写自己的代码setup.cfg
或setup.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 系统,则会调整值。