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

后端 未结 9 759
面向向阳花
面向向阳花 2021-01-31 01:33

I would like to see if there is any way of requiring a minimal python version.

I have several python modules that are requiring Python 2.6 due to the new exception handl

9条回答
  •  生来不讨喜
    2021-01-31 02:12

    To complement the existing, helpful answers:

    You may want to write scripts that run with both Python 2.x and 3.x, and require a minimum version for each.

    For instance, if your code uses the argparse module, you need at least 2.7 (with a 2.x Python) or at least 3.2 (with a 3.x Python).

    The following snippet implements such a check; the only thing that needs adapting to a different, but analogous scenario are the MIN_VERSION_PY2=... and MIN_VERSION_PY3=... assignments.

    As has been noted: this should be placed at the top of the script, before any other import statements.

    import sys
    
    MIN_VERSION_PY2 = (2, 7)    # min. 2.x version as major, minor[, micro] tuple
    MIN_VERSION_PY3 = (3, 2)    # min. 3.x version
    
    # This is generic code that uses the tuples defined above.
    if (sys.version_info[0] == 2 and sys.version_info < MIN_VERSION_PY2
          or
        sys.version_info[0] == 3 and sys.version_info < MIN_VERSION_PY3):
          sys.exit(
            "ERROR: This script requires Python 2.x >= %s or Python 3.x >= %s;"
            " you're running %s." % (
              '.'.join(map(str, MIN_VERSION_PY2)), 
              '.'.join(map(str, MIN_VERSION_PY3)), 
              '.'.join(map(str, sys.version_info))
            )
          )
    

    If the version requirements aren't met, something like the following message is printed to stderr and the script exits with exit code 1.

    This script requires Python 2.x >= 2.7 or Python 3.x >= 3.2; you're running 2.6.2.final.0.
    

    Note: This is a substantially rewritten version of an earlier, needlessly complicated answer, after realizing - thanks to Arkady's helpful answer - that comparison operators such as > can directly be applied to tuples.

提交回复
热议问题