JCGB
JCGB

Reputation: 533

How do I build a py2 wheel package, when setup.py runs with a Python version 3 interpreter?

I have a package that is supposed to be Python version 2 only but needs to be build running a version 3 interpreter.

The setup.py of this package looks something like hits:

from setuptools import setup

setup(
    python_requires="<3.0, >=2.7.5",
    classifiers=[
        'Programming Language :: Python :: 2',
        'Intended Audience :: Developers',
    ],
    # ... more keyword arguments ... 
 )

If I call python2 setup.py build bdist_wheel, I get:

$ ls dist
mypackage-0.3.dev14-py2-none-any.whl

If I run it with a version 3 interpreter, i.e. python3 setup.py build bdist_wheel, I get:

$ ls dist
mypackage-0.3.dev14-py3-none-any.whl

I would have expected that regardless of the interpreter version, I will get a py2 package, because I specified it with python_requires (and in the tags). My package build server only has a Python 3 interpreter.

How can I build a wheel that targets Python 2 when running setuptools with a Python 3 interpreter? Is that at all possible? Does the -py3-/-py2 in the filename mean something different than I think it does?

Upvotes: 3

Views: 1829

Answers (2)

joeforker
joeforker

Reputation: 41747

Try passing the python-tag argument to bdist_wheel:

python setup.py bdist_wheel --python-tag=py2

It could also be passed as

from setuptools import setup
setup(options={'bdist_wheel':{'python_tag':'py2'}})

Or in setup.cfg

Upvotes: 4

JCGB
JCGB

Reputation: 533

Modified from How to force a python wheel to be platform specific when building it?, this change to setup.py seems to work.

But I suspect there might be a less hacky way.

from setuptools import setup

try:
    from wheel.bdist_wheel import bdist_wheel as _bdist_wheel

    class bdist_wheel(_bdist_wheel):

        def finalize_options(self):
            _bdist_wheel.finalize_options(self)
            self.root_is_pure = False  # Mark us as not a pure python package

        def get_tag(self):
            python, abi, plat = _bdist_wheel.get_tag(self)
            python, abi = 'py2', 'none'  # python, abi, plat = 'py2', 'none', 'any'  
            return python, abi, plat
except ImportError:
    bdist_wheel = None

setup(      
    cmdclass={'bdist_wheel': bdist_wheel}
    # ... other keyword args ...
)

Edit:

With this solution the platform (plat) seems to change, because the resulting filename ends in -py2-none-linux_x86_64.whl.

I suspect that is a consequence of self.root_is_pure = False. Since I have no binaries in my package I assume it's safe to set the platform to any ant pure to True.

Edit2:

Another possible solution:

import sys
import setuptools

if 'bdist_wheel' in sys.argv:
    if not any(arg.startswith('--python-tag') for arg in sys.argv):
        sys.argv.extend(['--python-tag', 'py2'])

setuptools.setup(
    # ...
)

Upvotes: 4

Related Questions