有没有办法为我的基于平台的 Python 应用程序创建条件 requirements.txt 文件?

Is there a way to have a conditional requirements.txt file for my Python application based on platform?

我有一个 python 应用程序,我编写的应用程序与 Linux 和 Windows 平台都兼容。但是有一个问题...Windows 我需要的 python 软件包之一与 Linux 不兼容。幸运的是,Linux 上还有另一个包提供了相同的功能。所有其他依赖项在两个平台中都兼容。

我知道我可以有 2 个单独的需求文件来分别解决两个平台依赖关系。类似于 win_requirements.txt 和 linux_requirements.txt,但是这种方法感觉并不是最好的方法。

我想知道是否有一种方法可以让我只有一个 requirements.txt 文件,这样任何用户都可以使用 pip install -r requirements.txt 安装所有依赖项,而不管它们是什么平台?

也许是这样的??:

SOAPpy>=0.12.22
pycrypto>=2.6.1
suds>=0.4
Python-ldap>=2.4.19
paramiko>=1.15.2
nose>=1.3.4
selenium>=2.44.0
bottle>=0.12.8
CherryPy>=3.6.0
pika>=0.9.14
if platform.system() == 'Linux':
    wmi-client-wrapper>=0.0.12
else if platform.system() == 'Windows':
    WMI>=1.4.9

您可以创建一个 install.py 脚本并通过脚本调用 pip

import pip

_all_ = [
    "SOAPpy>=0.12.22",
    "pycrypto>=2.6.1",
    "suds>=0.4",
    "Python-ldap>=2.4.19",
    "paramiko>=1.15.2",
    "nose>=1.3.4",
    "selenium>=2.44.0",
    "bottle>=0.12.8",
    "CherryPy>=3.6.0",
    "pika>=0.9.14",
]

windows = ["wmi-client-wrapper>=0.0.12",]

linux = ["WMI>=1.4.9",]

darwin = []

def install(packages):
    for package in packages:
        pip.main(['install', package])

if __name__ == '__main__':

    from sys import platform

    install(_all_) 
    if platform == 'windows':
        install(windows)
    if platform.startswith('linux'):
        install(linux)
    if platform == 'darwin': # MacOS
        install(darwin)

另一种仅使用 requirements 文件来解决此问题的方法应该是使用 requirements

的继承

requirements.txt

SOAPpy>=0.12.22
pycrypto>=2.6.1
suds>=0.4
Python-ldap>=2.4.19
paramiko>=1.15.2
nose>=1.3.4
selenium>=2.44.0
bottle>=0.12.8
CherryPy>=3.6.0

windows.txt

-r requirements.txt
WMI>=1.4.9

linux.txt

-r requirements.txt
WMI>=1.4.9

那么就可以只调用平台等价的需求了。

pip install -r windows.txt
pip install -r linux.txt

您可以在分号后添加某些条件要求。对于 sys_platform 和 python_version.

特别有用

示例:

atomac==1.1.0; sys_platform == 'darwin'
futures>=3.0.5; python_version < '3.0'
futures>=3.0.5; python_version == '2.6' or python_version=='2.7'

显然您还可以排除库的特定版本:

futures>=3.0,!=3.0.5

它们在 PEP 508 and PEP 0345 (Environment Markers) but the syntax appears to follow the draft PEP 0496 中定义。

您可以在分号后向任何包添加附加要求。您可以通过 andor 限制任何具有多条件的包裹。更多条件:https://www.python.org/dev/peps/pep-0508/#environment-markers

示例:

futures>=3.0.5; python_version < '3.0'
futures>=3.0.5; python_version == '2.6' or python_version=='2.7'
futures>3 ; python_version >= "3.6" and sys_platform == "linux"
futures>3.3 ; python_version >= "3.6" and sys_platform == "darwin"

在 requirements.txt 文件中使用它

uwsgi==2.0.18; platform_system != "Windows"

在这种情况下,如果 运行 Windows

上没有,pip 将安装 uwsgi