requirements.txt depending on python version

PythonPip

Python Problem Overview


I'm trying to port a python2 package to python3 (not my own) using six so that it's compatible with both. However one of the packages listed in requirements.txt is now included in the python3 stdlib and the pypi version doesn't work in python3 so I want to conditionally exclude it. Doing this in setup.py is easy, I can just do something like:

if sys.version_info[0] == 2:
    requirements += py2_requirements
else:
    requirements += py3_requirements

But I would like requirements.txt to reflect the correct list too. I can't find anything on this in the pip documentation. so does anyone know how to do it, or if it is even possible?

Python Solutions


Solution 1 - Python

You can use the environment markers to achieve this in requirements.txt since pip 6.0:

SomeProject==5.4; python_version < '2.7'
SomeProject; sys_platform == 'win32'

It is supported by setuptools too by declaring extra requirements in setup.py:

setup(
    ...
    install_requires=[
        'six',
        'humanize',
    ],
    extras_require={
        ':python_version == "2.7"': [
            'ipaddress',
        ],
    },
)

See also requirement specifiers. And Strings for the string versions of corresponding Python commands.

Solution 2 - Python

You can create multiple requirements files, put those common packages in a common file, and include them in another pip requirements file with -r file_path

requirements/
  base.txt
  python2.txt
  python3.txt

python2.txt:

-r base.txt
Django==1.4 #python2 only packages

python3.txt:

-r base.txt
Django==1.5 #python3 only packages

pip install -r requirements/python2.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaquavitaeView Question on Stackoverflow
Solution 1 - PythonJiangge ZhangView Answer on Stackoverflow
Solution 2 - PythonLeonardo.ZView Answer on Stackoverflow