File: pyversion.py

package info (click to toggle)
dune-common 2.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,048 kB
  • sloc: cpp: 54,403; python: 4,136; sh: 1,657; makefile: 17
file content (50 lines) | stat: -rw-r--r-- 1,817 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
# SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
#
# This python script tries to figure out the version of a given python
# package. This is only intended to be used from DunePythonFindPackage.cmake
#
# There is no unified way of specifying the version of a python package. This
# script implements some methods. For discussion on the implemented methods see
# http://stackoverflow.com/questions/20180543
#

import sys
import warnings

# Load the module name passed as argument (this avoids the need for a template
# to be configured to put the package name inhere)
modstr = sys.argv[1]

with warnings.catch_warnings():
    # suppress any warnings which may be raised on import (e.g. virtualenv 20.2.2)
    warnings.simplefilter("ignore")

    module = __import__(modstr)
    # The most common mechanism is module.__version__
    if hasattr(module, '__version__'):
        sys.stdout.write(module.__version__)
        sys.exit(0)

if sys.version_info.major == 3 and sys.version_info.minor >= 8:
    import importlib.metadata
    try:
        sys.stdout.write(importlib.metadata.version(modstr))
        sys.exit(0)
    except importlib.metadata.PackageNotFoundError:
        pass

# Alternative implementation: through pip (pip itself implement pip.__version__,
# so we never get here, when checking the version of pip itself), only works if
# package name and distribution name are the same
try:
    import pkg_resources
    for package in pkg_resources.working_set:
        if package.project_name == modstr and package.has_version():
            sys.stdout.write(package.version)
            sys.exit(0)
except ImportError:
    pass

# We ran out of options: give up on this one
sys.exit(1)