requirements.txt depending on python version

2019-01-13 19:50发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

I don't think that it is possible because the requirements.txt file is just a text file. The closest thing I can think of would be to comment out the package in requirements.txt with a comment above stating that it should be installed for python2.6. Maybe it would be worth adding some code in to check the python version?

import sys
if sys.version_info.major == 2:
try:
    import blah
except ImportError:
    sys.stderr.write("Yo, pip install blah")
    sys.exit(1)


回答4:

See my answer https://stackoverflow.com/a/25078063/302521 and this script: https://gist.github.com/pombredanne/72130ee6f202e89c13bb



标签: python pip