首页 > 解决方案 > 仅当平台为 Windows 时才安装 python 依赖项

问题描述

我想将pywin32条件Python 依赖项添加到setup.pywhenplatform_system == Windows

谁能给我一个关于如何使它工作的提示?

在探索了stackoverflow之后,还没有找到python2.7的答案。

我正在使用 Python 2.7,setuptools 28.xx,pip 19.xx Egg-info 是自动构建的。

from setuptools import setup, find_packages
import platform

platform_system = platform.system()

setup(
    name=xxx,
    version=xxx,
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'matplotlib',
    ],
    extras_require={
        'platform_system=="Windows"': [
            'pywin32'
        ]
    },
    entry_points='''
        [console_scripts]
        xx:xx
    ''',
)

我不明白这些键是如何extras_require工作的。会platform_system参考platform_system前面的定义吗?

我也试过:

from setuptools import setup, find_packages
import platform

setup(
    xxx
    install_requires=[
        'matplotlib',
        'pywin32;platform_system=="Windows"',
    ],
)

但这仅适用于python_version>=3.4

此外,看起来https://www.python.org/dev/peps/pep-0508/对我不起作用。

标签: python-2.7dependenciessetuptools

解决方案


检查 Python操作系统模块

os.name 导入的操作系统相关模块的名称。当前已注册以下名称:'posix'、'nt'、'os2'、'ce'、'java'、'riscos'。

nt用于 Windows 操作系统。

import os

if os.name == 'nt':
    # Windows-specific code here...

您也可以检查sys.platform

sys.platform 例如,此字符串包含一个平台标识符,可用于将特定于平台的组件附加到 sys.path。

import sys

if sys.platform.startswith('win32'):
    # Windows-specific code here...

编辑: 根据您的问题,如果操作系统是 Windows,您想安装 pywin32。我认为这段代码会帮助你:

import sys


INSTALL_REQUIRES = [
    # ...
]
EXTRAS_REQUIRE = {
    # ...
}

if sys.platform.startswith('win32'):
    INSTALL_REQUIRES.append("pywin32")

setup(
    # ...
    install_requires=INSTALL_REQUIRES,
    extras_require=EXTRAS_REQUIRE,
)

推荐阅读