Search code examples
python-2.7dependenciessetuptools

Install python dependency only when platform is Windows


I want to add pywin32 as Conditional Python Dependencies to setup.py when platform_system == Windows

Could anyone give me a hint on how to make it work?

After exploring the stackoverflow, haven't found a answer to python2.7.

I'm using Python 2.7, setuptools 28.x.x, pip 19.x.x. Egg-info is auto-build.

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
    ''',
)

I don't understand how the keys in extras_require work. Would platform_system refer to the definition of platform_system in the front?

I also tried:

from setuptools import setup, find_packages
import platform

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

But this is available only for python_version>=3.4

Also, it looks like https://www.python.org/dev/peps/pep-0508/ doesn't work for me.


Solution

  • Check Python os module

    os.name The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'.

    and nt uses for windows OS.

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

    You can check sys.platform too.

    sys.platform This string contains a platform identifier that can be used to append platform-specific components to sys.path, for instance.

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

    Edited: base on your question, you want to install pywin32 if OS is Windows. I think this code will help you:

    import sys
    
    
    INSTALL_REQUIRES = [
        # ...
    ]
    EXTRAS_REQUIRE = {
        # ...
    }
    
    if sys.platform.startswith('win32'):
        INSTALL_REQUIRES.append("pywin32")
    
    setup(
        # ...
        install_requires=INSTALL_REQUIRES,
        extras_require=EXTRAS_REQUIRE,
    )