Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure the script is executed by a specific version of python? [duplicate]

As the question asks, I want to be sure that the script is executed by a specific version of python, say =>3.5.2.

How can I make sure that the script when executed is called by the specific version.

This check should be done in the python script itself.

It could be better if the solution is platform independent.

like image 971
penta Avatar asked Oct 15 '25 18:10

penta


1 Answers

Just add this to the start of your script:

import sys

assert sys.version_info >= (3, 5, 2), "Python version too low."

Or if you prefer without assert:

import sys

if sys.version_info < (3, 5, 2):
    raise EnvironmentError("Python version too low.")

Or little bit more verbosely, but this will actually inform what version is needed:

import sys

MIN_VERSION = (3, 5, 2)

if sys.version_info < MIN_VERSION:
    raise EnvironmentError(
        "Python version too low, required at least {}".format(
            '.'.join(str(n) for n in MIN_VERSION)
        )
    )

Example output:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    raise EnvironmentError(
OSError: Python version too low, required at least 3.5.2

 

The specified minimum version tuple can be as precise as you want. These are all valid:

MIN = (3,)
MIN = (3, 5)
MIN = (3, 5, 2)
like image 123
ruohola Avatar answered Oct 17 '25 08:10

ruohola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!