Python require minimum version required

Requirements.txt in python package

E.g. start your script like so: Solution 3: Starting with version 9.0.0 pip supports Requires-Python field in distribution’s metadata which can be written by setuptools starting with version 24-2-0. So all requirements are going to be installed by old version of and the version specified in will be available afterwards.

How to write Python code that is able to properly require a minimal python version?

You can take advantage of the fact that Python will do the right thing when comparing tuples:

#!/usr/bin/python import sys MIN_PYTHON = (2, 6) if sys.version_info < MIN_PYTHON: sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON) 

You should not use any Python 2.6 features inside the script itself. Also, you must do your version check before importing any of the modules requiring a new Python version.

E.g. start your script like so:

#!/usr/bin/env python import sys if sys.version_info[0] != 2 or sys.version_info[1] < 6: print("This script requires Python version 2.6") sys.exit(1) # rest of script, including real initial imports, here 

Starting with version 9.0.0 pip supports Requires-Python field in distribution's metadata which can be written by setuptools starting with version 24-2-0. This feature is available through python_requires keyword argument to setup function.

Читайте также:  Python threadpoolexecutor map example

To take advantage of this feature one has to package the project/script first if not already done. This is very easy in typical case and should be done nonetheless as it allows users to easily install, use and uninstall given project/script. Please see python packaging user guide for details.

Python - How to install from requirements.txt?, If you get some path name instead of the version number in the requirements.txt file, use this pip command to work around it. pip list --format=freeze > requirements.txt Share

Requirements.txt in python package

The requirements.txt is a file where one specifies dependencies. For example your program can have dependency on Django or we can say the requirements.txt file in a django project describes the packages that needs to be installed for successfully running a project.

Talking about the sub-modules: Suppose you have specified django in the requirements.txt file, now you don't need to specify any sub-modules (like 'django.shortcuts') in the requirements.txt file. Because they are already included in the django module.

from django.shortcuts import path

Now for separate modules (like pillow) that need to be specified in the requirements.txt file, you don't need to write

You can just write pillow in a separate line with other modules like:

You can also use the below command to do so:

In your case file_name will be requirements.txt. This will add all the third-party module names in the requirements.txt file.

How to write Python code that is able to properly, Sure, using old-style formatting will make the test work with older versions. I didn't do that because I have f-strings throughout the rest of my Python source, so using old-style formatting just for that test still won't allow the …

How to specify version ranges in install_requires (setuptools, distribute)

According to the documentation, your syntax should work correctly. The documentation states that:

setuptools and pkg_resources use a common syntax for specifying a project's required dependencies. This syntax consists of a project's PyPI name, optionally followed by a comma-separated list of "extras" in square brackets, optionally followed by a comma-separated list of version specifiers. A version specifier is one of the operators , =, == or !=, followed by a version identifier.

The documentation gives a simple example like this:

docutils >= 0.3 # comment lines and \ continuations are allowed in requirement strings BazSpam ==1.1, ==1.2, ==1.3, ==1.4, ==1.5, \ ==1.6, ==1.7 # and so are line-end comments 

To expand upon that, if you want your package to require a version of docutils greater than version 0.3 but less than version 0.5, code like this would work:

  1. The documentation also states that redundant/overlapping dependency specifications will be combined internally, so docutils >= 0.3, >=0.2 would be combined into docutils >= 0.3 .
  2. Also, be careful about specifying conflicting version numbers, which "is meaningless and may therefore produce bizarre results." For example, I don't know why you would, but don't use this: docutils >= 0.3,

Be wary of involuntary beta tests. Package maintainers sometimes release incompatible, incomplete, or broken a, b, and c releases to general audiences without warning. The next time you run setup.py in a fresh virtualenv, you might pull down one of these poisoned eggs, and suddenly your program will break.

When setuptools does something unexpected, trying using verlib to model your version comparisons. Verlib is a pretty good fit as long as your versions are normalized and non-contradictory. Here is an example that demonstrates the potentially counter-intuitive ordering of normalized versions:

#!/usr/bin/env python from verlib import NormalizedVersion as V assert (V("0.7.9") < V("0.8a0") < V("0.8a1") < V("0.8b0") < V("0.8b1") < V("0.8b2") < V("0.8.0") < V("0.8.1a0") < V("0.8.1") < V("0.9") < V("1.0a3") < V("1.0b2") < V("1.0b20") < V("1.0c0") < V("1.0") < V("1.0.1")) assert (V("0.7.9") < V("0.8.0a0") < V("0.8.0a1") < V("0.8.0b0") < V("0.8.0b1") < V("0.8.0b2") < V("0.8.0") < V("0.8.1a0") < V("0.8.1") < V("0.9") < V("1.0a3") < V("1.0b2") < V("1.0b20") < V("1.0c0") < V("1.0") < V("1.0.1")) print "Version comparisons are sane." 

The notation mentioned in OP's question, >= 0.5.0, < 0.7.0 , already works.

How to use requirements.txt to install all dependencies in, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Specify 'pip' version in requirements.txt

Please note that pip version listed in requirements.txt is going to be installed along with other requirements. So all requirements are going to be installed by old version of pip and the version specified in requirements.txt will be available afterwards.

virtualenv /path/to/my/desired/venv/ source /path/to/my/desired/venv/bin/activate pip install -U pip pip install -r requirements.txt 

What you experience is caused by an old version of python-virtualenv delivered with Ubuntu 14.04. You should remove the Ubuntu package and install via pip:

sudo pip install virtualenv 

Then make sure you have the newest pip installed as well.

And you should get that version installed in new virtual environments.

How to manage multiple Python versions and virtual, This allows pyenv to activate and deactivate environments automatically when moving directories. To create a new virtual environment, use: $ pyenv virtualenv // for example $ pyenv virtualenv 2.7.10 my-virtual-env-2.7.10. Existing environments can be listed with: $ pyenv …

Источник

Ensuring minimum version for imported Python package

Most Python packages follow the convention that the version is provided as a string at [package_name].version.version . Let's use Numpy as an example. Say I wanted to import Numpy but ensure that the minimum version is 1.18.1 . This is what I do currently:

import numpy as np if tuple(map(int, np.version.version.split('.'))) < (1, 18, 1): raise ImportError('Numpy version too low! Must be >= 1.18.1') 

While this seems to work, it requires me to import the package before the version can be checked. It would be nice to not have to import the package if the condition is not satisfied. It also seems a bit "hacky" and it feels like there's probably a method using the Python standard library that does this. Something like version('numpy') > '1.18.1' . But I haven't been able to find one. Is there a way to check the version of a package BEFORE importing it within the bounds of the Python standard library? I am looking for a programmatic solution in Python code. Telling me to use a requirements.txt or pip install is not answering the question. Edit to add context: Adding this package to my requirements.txt is not useful as the imported package is supposed to be an optional dependency. This code would go in a submodule that is optionally loaded in the __init__.py via a try statement. Essentially, some functionality of the package is only available if a package of minimum version is found and successfully imported.

Usually one controls what version of packages they get with a requirements.txt file or more recently using python-poetry to manage versions in a project. This does not answer your question about how to handle it in python code though.

In my case, I am concerned with optional dependencies. So, I can't have the package listed in the requirements.txt , but I have submodules in the package that are loaded up if the optional dependency exists.

2 Answers 2

Run pip show for a specific package using subprocess then parse the result to compare the installed version to your requirment(s).

>>> import subprocess >>> result = subprocess.run(['pip', 'show', 'numpy'], stdout=subprocess.PIPE) >>> result.stdout b'Name: numpy\r\nVersion: 1.17.4\r\nSummary: NumPy is the fundamental package for array computing with Python.\r\nHome-page: https://www.numpy.org\r\nAuthor: Travis E. Oliphant et al.\r\nAuthor-email: None\r\nLicense: BSD\r\nLocation: c:\\python38\\lib\\site-packages\r\nRequires: \r\nRequired-by: scipy, scikit-learn, perfplot, pandas, opencv-python, matplotlib\r\n' >>> result = subprocess.run(['pip', 'show', 'pandas'], stdout=subprocess.PIPE) >>> for thing in result.stdout.splitlines(): . print(thing) b'Name: pandas' b'Version: 0.25.3' b'Summary: Powerful data structures for data analysis, time series, and statistics' b'Home-page: http://pandas.pydata.org' b'Author: None' b'Author-email: None' b'License: BSD' b'Location: c:\\python38\\lib\\site-packages' b'Requires: numpy, python-dateutil, pytz' b'Required-by: ' >>> >>> from email.header import Header >>> result = subprocess.run(['pip', 'show', 'pandas'], stdout=subprocess.PIPE) >>> h = Header(result.stdout) >>> print(str(h)) Name: pandas Version: 0.25.3 Summary: Powerful data structures for data analysis, time series, and statistics Home-page: http://pandas.pydata.org Author: None Author-email: None License: BSD Location: c:\python38\lib\site-packages Requires: python-dateutil, pytz, numpy Required-by: >>> d = <> >>> for line in result.stdout.decode().splitlines(): . k,v = line.split(':',1) . d[k] = v >>> d['Version'] ' 0.25.3' >>> 
>>> result = subprocess.run(['pip', 'list'], stdout=subprocess.PIPE) >>> for thing in result.stdout.splitlines(): print(thing) b'Package Version ' b'---------------- ----------' b'-illow 6.2.1 ' b'aiohttp 3.6.2 ' b'appdirs 1.4.3 ' . 

Источник

How to detect minimum version of python that a script required

I have built an application with python. How can I detect minimum version of Python that my application needs? Like Django , in that website it tells you the minimum version of python that it required (example: 2.6.6 and later). It means I wanna tell to user what minimum version of python he should install on his system

You mean at runtime so the script can tell the user to use a newer version, or so you know what version of Python to use by looking at the code?

That's a question of experience and reading the docs; what features does your script use, and when where these added to the language.

Do you have a test suite? Run it with older versions and see if it passes. There is no automated method of testing for feature use.

2 Answers 2

I know this is an old post, but I've recently started a project called Vermin that tries to detect the minimum required Python versions needed to run code. It will do what you request, @Mortezaipo.

There isn't really an automated way to check what features your code is using and correlate that to specific Python versions. If your code relies on fixed bugs or additional keywords to existing methods, the version detection gets harder still.

Generally speaking, you set the minimal version based on experience and knowledge of what features you are using; you can check the What's New documentation.

If you have a comprehensive test suite, you could just run that on older Python versions; if all your tests pass you support that older version.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью