Use pkg_resources to determine the installed package version.
321554
def from_pkg(self):
        
        if self._version is None:
            frame = caller(1)
            pkg = frame.f_globals.get('__package__')
            if pkg is not None:
                self._version = pkg_version(pkg)
        return self
825821
def guess_version(pkg_key, default='?'):
    
    try:
        m = import_module(pkg_key)
    except ImportError:
        return default
    else:
        return getattr(m, '__version__', default)
987731
def package_install(name, **kwargs):
    '''
    
    '''
    cmd = 'pkg_install ' + name
    if kwargs.get('version', False):
        cmd += ' ' + kwargs['version']

    # Send the command to execute
    out, err = DETAILS['server'].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)
1204782
def check_dependencies():
    

    # Check that git is installed
    if not shutil.which("git"):
        raise Error(_("You don't have git. Install git, then re-run!"))

    # Check that git --version > 2.7
    version = subprocess.check_output(["git", "--version"]).decode("utf-8")
    matches = re.search(r"^git version (\d+\.\d+\.\d+).*$", version)
    if not matches or pkg_resources.parse_version(matches.group(1)) < pkg_resources.parse_version("2.7.0"):
        raise Error(_("You have an old version of git. Install version 2.7 or later, then re-run!"))
313961
def get_package_version():
    """"""
    base = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(base, "firepit/__init__.py")) as pkg:
        for line in pkg:
            m = version.match(line.strip())
            if not m:
                continue
            return ".".join(m.groups()[0].split(", "))
1092202
def is_deb_package_installed(pkg):
    

    with settings(hide('warnings', 'running', 'stdout', 'stderr'),
                  warn_only=True, capture=True):

        result = sudo('dpkg-query -l "%s" | grep -q ^.i' % pkg)
        return not bool(result.return_code)
405361
def was_installed_by_pip(pkg):
    # type: (str) -> bool
    
    try:
        dist = pkg_resources.get_distribution(pkg)
        return (dist.has_metadata('INSTALLER') and
                'pip' in dist.get_metadata_lines('INSTALLER'))
    except pkg_resources.DistributionNotFound:
        return False
216321
def get_version(mod, default="0.0.0"):
    
    name = mod
    if hasattr(mod, "__name__"):
        name = mod.__name__

    try:
        import pkg_resources

        return pkg_resources.get_distribution(name).version

    except Exception as e:
        LOG.warning("Can't determine version for %s: %s", name, e, exc_info=e)
        return default
320571
def main():
    """"""
    try:
        pkg_version = Update()
        if pkg_version.updatable():
            pkg_version.show_message()
        metadata = control.retreive_metadata()
        parser = parse_options(metadata)
        argvs = sys.argv
        if len(argvs) <= 1:
            parser.print_help()
            sys.exit(1)
        args = parser.parse_args()
        control.print_licences(args, metadata)
        control.check_repository_existence(args)
        control.check_package_existence(args)
        control.generate_package(args)
    except (RuntimeError, BackendFailure, Conflict) as exc:
        sys.stderr.write('{0}\n'.format(exc))
        sys.exit(1)
1256839
def pkg_upgrade(repo, skip, flag):
    
    Msg().checking()
    PACKAGES_TXT = RepoInit(repo).fetch()[0]
    pkgs_for_upgrade = []
    # name = data[0]
    # location = data[1]
    # size = data[2]
    # unsize = data[3]
    data = repo_data(PACKAGES_TXT, repo, flag="")
    for pkg in installed():
        status(0.0005)
        inst_pkg = split_package(pkg)
        for name in data[0]:
            if name:    # this tips because some pkg_name is empty
                repo_pkg = split_package(name[:-4])
            if (repo_pkg[0] == inst_pkg[0] and
                LooseVersion(repo_pkg[1]) > LooseVersion(inst_pkg[1]) and
                repo_pkg[3] >= inst_pkg[3] and
                    inst_pkg[0] not in skip and
                    repo_pkg[1] != "blacklist"):
                pkgs_for_upgrade.append(repo_pkg[0])
    Msg().done()
    if "--checklist" in flag:
        pkgs_for_upgrade = choose_upg(pkgs_for_upgrade)
    return pkgs_for_upgrade
31094
def is_installed(name):
    
    pkgs = installed_packages()
    for pkge in pkgs:
        if pkge.name == name:
            return True
    return False
101960
def get_version(package_name):
    
    module = 'prosper.' + package_name + '._version'
    package = importlib.import_module(module)

    version = package.__version__

    return version
112453
def get_version(project_dir=os.curdir):
    
    if 'LAGO_VERSION' in os.environ and os.environ['LAGO_VERSION']:
        return os.environ['LAGO_VERSION']

    version = None
    pkg_info_file = os.path.join(project_dir, 'PKG-INFO')
    version_manager = os.path.join(project_dir, 'scripts/version_manager.py')
    if os.path.exists(pkg_info_file):
        with open(pkg_info_file) as info_fd:
            for line in info_fd.readlines():
                if line.startswith('Version: '):
                    version = line.split(' ', 1)[-1]

    elif os.path.exists(version_manager):
        version = check_output([version_manager, project_dir,
                                'version']).strip()

    if version is None:
        raise RuntimeError('Failed to get package version')

    # py3 compatibility step
    if not isinstance(version, str) and isinstance(version, bytes):
        version = version.decode()

    return version
772998
def get_installed_version(dist_name, working_set=None):
    """"""
    # Create a requirement that we'll look for inside of setuptools.
    req = pkg_resources.Requirement.parse(dist_name)

    if working_set is None:
        # We want to avoid having this cached, so we need to construct a new
        # working set each time.
        working_set = pkg_resources.WorkingSet()

    # Get the installed distribution from our working set
    dist = working_set.find(req)

    # Check to see if we got an installed distribution or not, if we did
    # we want to return it's version.
    return dist.version if dist else None
559813
def package_ensure_apt(*packages):
    """"""
    package = " ".join(packages)
    status = run("dpkg-query -W -f='${{Status}} ' {p}; true".format(p=package))
    status = status.lower()
    if 'no packages found' in status or 'not-installed' in status:
        sudo("apt-get --yes install " + package)
        return False
    else:
        return True
758206
def guess_version_by_running_live_package(
    pkg_key, default="?"
):  # type: (str,str) -> Any
    
    try:
        m = import_module(pkg_key)
    except ImportError:
        return default
    else:
        return getattr(m, "__version__", default)
469999
def _check_pkg_version_format(pkg):
    '''
    
    '''

    ret = {'result': False, 'comment': None,
           'prefix': None, 'version_spec': None}

    if not HAS_PIP:
        ret['comment'] = (
            'An importable Python 2 pip module is required but could not be '
            'found on your system. This usually means that the system\'s pip '
            'package is not installed properly.'
        )

        return ret

    from_vcs = False
    try:
        # Get the requirement object from the pip library
        try:
            # With pip < 1.2, the __version__ attribute does not exist and
            # vcs+URL urls are not properly parsed.
            # The next line is meant to trigger an AttributeError and
            # handle lower pip versions
            log.debug('Installed pip version: %s', pip.__version__)
            install_req = _from_line(pkg)
        except AttributeError:
            log.debug('Installed pip version is lower than 1.2')
            supported_vcs = ('git', 'svn', 'hg', 'bzr')
            if pkg.startswith(supported_vcs):
                for vcs in supported_vcs:
                    if pkg.startswith(vcs):
                        from_vcs = True
                        install_req = _from_line(
                            pkg.split('{0}+'.format(vcs))[-1]
                        )
                        break
            else:
                install_req = _from_line(pkg)
    except (ValueError, InstallationError) as exc:
        ret['result'] = False
        if not from_vcs and '=' in pkg and '==' not in pkg:
            ret['comment'] = (
                'Invalid version specification in package {0}. \'=\' is '
                'not supported, use \'==\' instead.'.format(pkg)
            )
            return ret
        ret['comment'] = (
            'pip raised an exception while parsing \'{0}\': {1}'.format(
                pkg, exc
            )
        )
        return ret

    if install_req.req is None:
        # This is most likely an url and there's no way to know what will
        # be installed before actually installing it.
        ret['result'] = True
        ret['prefix'] = ''
        ret['version_spec'] = []
    else:
        ret['result'] = True
        try:
            ret['prefix'] = install_req.req.project_name
            ret['version_spec'] = install_req.req.specs
        except Exception:
            ret['prefix'] = re.sub('[^A-Za-z0-9.]+', '-', install_req.name)
            if hasattr(install_req, "specifier"):
                specifier = install_req.specifier
            else:
                specifier = install_req.req.specifier
            ret['version_spec'] = [(spec.operator, spec.version) for spec in specifier]

    return ret