List the packages currently installed in a dict::

        {'<package_name>': '<version>'}

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_pkgs
        salt '*' pkg.list_pkgs versions_as_list=True
335424
def list_pkgs(versions_as_list=False, **kwargs):
    '''
    
    '''
    versions_as_list = salt.utils.data.is_true(versions_as_list)
    # not yet implemented or not applicable
    if any([salt.utils.data.is_true(kwargs.get(x))
            for x in ('removed', 'purge_desired')]):
        return {}

    if 'pkg.list_pkgs' in __context__:
        if versions_as_list:
            return __context__['pkg.list_pkgs']
        else:
            ret = copy.deepcopy(__context__['pkg.list_pkgs'])
            __salt__['pkg_resource.stringify'](ret)
            return ret

    cmd = ['apk', 'info', '-v']
    ret = {}
    out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
    for line in salt.utils.itertools.split(out, '\n'):
        pkg_version = '-'.join(line.split('-')[-2:])
        pkg_name = '-'.join(line.split('-')[:-2])
        __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)

    __salt__['pkg_resource.sort_pkglist'](ret)
    __context__['pkg.list_pkgs'] = copy.deepcopy(ret)
    if not versions_as_list:
        __salt__['pkg_resource.stringify'](ret)
    return ret
787624
def list_packages(self, **kwargs):
        
        get_kwargs = {}
        get_kwargs['mask'] = kwargs.get('mask', PACKAGE_MASK)

        if 'filter' in kwargs:
            get_kwargs['filter'] = kwargs['filter']

        packages = self.package_svc.getAllObjects(**get_kwargs)

        return [package for package in packages if package['isActive']]
925650
def filter_installed_packages(packages):
    """"""
    yb = yum.YumBase()
    package_list = yb.doPackageLists()
    temp_cache = {p.base_package_name: 1 for p in package_list['installed']}

    _pkgs = [p for p in packages if not temp_cache.get(p, False)]
    return _pkgs
992363
def post_versions_list(self, updater_name=None, updater_id=None,
                           post_id=None, start_id=None):
        
        params = {
            'search[updater_name]': updater_name,
            'search[updater_id]': updater_id,
            'search[post_id]': post_id,
            'search[start_id]': start_id
            }
        return self._get('post_versions.json', params)
271109
def _repo_packages(self, args, search=False):
        '''
        
        '''
        packages = []
        repo_metadata = self._get_repo_metadata()
        for repo in repo_metadata:
            for pkg in repo_metadata[repo]['packages']:
                if args[1] in pkg:
                    version = repo_metadata[repo]['packages'][pkg]['info']['version']
                    release = repo_metadata[repo]['packages'][pkg]['info']['release']
                    packages.append((pkg, version, release, repo))
        for pkg in sorted(packages):
            self.ui.status(
                '{0}\t{1}-{2}\t{3}'.format(pkg[0], pkg[1], pkg[2], pkg[3])
            )
        return packages
1135210
def list_pkgs(versions_as_list=False, **kwargs):
    '''
    
    '''
    versions_as_list = salt.utils.data.is_true(versions_as_list)
    # not yet implemented or not applicable
    if any([salt.utils.data.is_true(kwargs.get(x))
            for x in ('removed', 'purge_desired')]):
        return {}

    if 'pkg.list_pkgs' in __context__:
        if versions_as_list:
            return __context__['pkg.list_pkgs']
        else:
            ret = copy.deepcopy(__context__['pkg.list_pkgs'])
            __salt__['pkg_resource.stringify'](ret)
            return ret

    pkgin = _check_pkgin()
    ret = {}

    out = __salt__['cmd.run'](
        [pkgin, 'ls'] if pkgin else ['pkg_info'],
        output_loglevel='trace')

    for line in out.splitlines():
        try:
            # Some versions of pkgin check isatty unfortunately
            # this results in cases where a ' ' or ';' can be used
            pkg, ver = re.split('[; ]', line, 1)[0].rsplit('-', 1)
        except ValueError:
            continue
        __salt__['pkg_resource.add_pkg'](ret, pkg, ver)

    __salt__['pkg_resource.sort_pkglist'](ret)
    __context__['pkg.list_pkgs'] = copy.deepcopy(ret)
    if not versions_as_list:
        __salt__['pkg_resource.stringify'](ret)
    return ret
988878
def get_version_of_tools():
    
    response = []
    for tool in TOOLS_USED:
        pkg_name = tool["pkg_name"]
        try:
            tool_module = import_module(pkg_name)
        except ImportError as ex:
            logger.warning("can't import module %s: %r", pkg_name, ex)
        else:
            version = getattr(tool_module, "__version__", None)
            if version is None:
                logger.warning("tool %s doesn't have __version__", pkg_name)
            else:
                response.append({
                    "name": tool.get("display_name", pkg_name),
                    "version": version,
                    "path": tool_module.__file__,
                })
    return response
737043
def _list_files(self, args):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package name must be specified')

        package = args[-1]

        files = self._pkgdb_fun('list_files', package, self.db_conn)
        if files is None:
            raise SPMPackageError('package {0} not installed'.format(package))
        else:
            for file_ in files:
                if self.opts['verbose']:
                    status_msg = ','.join(file_)
                else:
                    status_msg = file_[0]
                self.ui.status(status_msg)
1188394
def _get_patches(installed_only=False):
    '''
    
    '''
    patches = {}

    cmd = [_yum(), '--quiet', 'updateinfo', 'list', 'all']
    ret = __salt__['cmd.run_stdout'](
        cmd,
        python_shell=False
    )
    for line in salt.utils.itertools.split(ret, os.linesep):
        inst, advisory_id, sev, pkg = re.match(r'([i|\s]) ([^\s]+) +([^\s]+) +([^\s]+)',
                                               line).groups()
        if inst != 'i' and installed_only:
            continue
        patches[advisory_id] = {
            'installed': True if inst == 'i' else False,
            'summary': pkg
        }
    return patches
861359
def list_releases():
    
    response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME))
    if response:
        data = response.json()

        releases_dict = data.get('releases', {})

        if releases_dict:
            for version, release in releases_dict.items():
                release_formats = []
                published_on_date = None
                for fmt in release:
                    release_formats.append(fmt.get('packagetype'))
                    published_on_date = fmt.get('upload_time')

                release_formats = ' | '.join(release_formats)
                print('{:<10}{:>15}{:>25}'.format(version, published_on_date, release_formats))
        else:
            print('No releases found for {}'.format(PYPI_PACKAGE_NAME))
    else:
        print('Package "{}" not found on Pypi.org'.format(PYPI_PACKAGE_NAME))
1359197
def installed_packages(self):
        
        freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
        return list(map(split_package_name, filter(None, self._execute_pip(
                ['freeze'] + freeze_options).split(linesep))))
968857
def get_package_version(self):
        
        output = subprocess.check_output([
            '{}'.format(self.python),
            'setup.py',
            '--version',
        ]).decode()
        return output.rstrip()
73619
def list_of_installed(self, repo, name):
        
        all_installed_names = []
        all_installed_packages = find_package("", self.meta.pkg_path)
        for inst in all_installed_packages:
            if repo == "sbo" and inst.endswith("_SBo"):
                name = split_package(inst)[0]
                all_installed_names.append(name)
            else:
                if name:
                    all_installed_names.append(split_package(inst)[0])
                else:
                    all_installed_names.append(inst)
        return all_installed_names
335980
def find_installed_packages(self):
        
        list_command = subprocess.Popen(self.list_command, shell=True, stdout=subprocess.PIPE)
        stdout, stderr = list_command.communicate()
        if list_command.returncode != 0:
            raise SystemDependencyError("The command to list the installed system packages failed! ({command})",
                                        command=self.list_command)
        installed_packages = sorted(stdout.decode().split())
        logger.debug("Found %i installed system package(s): %s", len(installed_packages), installed_packages)
        return installed_packages
760681
def list_upgrades(bin_env=None,
                  user=None,
                  cwd=None):
    '''
    
    '''
    cmd = _get_pip_bin(bin_env)
    cmd.extend(['list', '--outdated'])

    pip_version = version(bin_env)
    # Pip started supporting the ability to output json starting with 9.0.0
    min_version = '9.0'
    if salt.utils.versions.compare(ver1=pip_version,
                                   oper='>=',
                                   ver2=min_version):
        cmd.append('--format=json')

    cmd_kwargs = dict(cwd=cwd, runas=user)
    if bin_env and os.path.isdir(bin_env):
        cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}

    result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
    if result['retcode']:
        raise CommandExecutionError(result['stderr'], info=result)

    packages = {}
    # Pip started supporting the ability to output json starting with 9.0.0
    # Older versions will have to parse stdout
    if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
        # Pip versions < 8.0.0 had a different output format
        # Sample data:
        # pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
        # psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
        # pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
        # pycparser (Current: 2.17 Latest: 2.18 [sdist])
        if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
            logger.debug('pip module: Old output format')
            pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')

        # New output format for version 8.0.0+
        # Sample data:
        # pip (8.0.0) - Latest: 10.0.1 [wheel]
        # psutil (5.2.2) - Latest: 5.4.5 [wheel]
        # pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
        # pycparser (2.17) - Latest: 2.18 [sdist]
        else:
            logger.debug('pip module: New output format')
            pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')

        for line in result['stdout'].splitlines():
            match = pat.search(line)
            if match:
                name, version_ = match.groups()
            else:
                logger.error('Can\'t parse line \'%s\'', line)
                continue
            packages[name] = version_

    else:
        logger.debug('pip module: JSON output format')
        try:
            pkgs = salt.utils.json.loads(result['stdout'], strict=False)
        except ValueError:
            raise CommandExecutionError('Invalid JSON', info=result)

        for pkg in pkgs:
            packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
                                                       pkg['latest_filetype'])

    return packages
1224461
def _get_pkg_info(*packages, **kwargs):
    '''
    
    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    failhard = kwargs.pop('failhard', True)
    if kwargs:
        salt.utils.args.invalid_kwargs(kwargs)

    if __grains__['os'] == 'Ubuntu' and __grains__['osrelease_info'] < (12, 4):
        bin_var = '${binary}'
    else:
        bin_var = '${Package}'

    ret = []
    cmd = "dpkg-query -W -f='package:" + bin_var + "\\n" \
          "revision:${binary:Revision}\\n" \
          "arch:${Architecture}\\n" \
          "maintainer:${Maintainer}\\n" \
          "summary:${Summary}\\n" \
          "source:${source:Package}\\n" \
          "version:${Version}\\n" \
          "section:${Section}\\n" \
          "installed_size:${Installed-size}\\n" \
          "size:${Size}\\n" \
          "MD5:${MD5sum}\\n" \
          "SHA1:${SHA1}\\n" \
          "SHA256:${SHA256}\\n" \
          "origin:${Origin}\\n" \
          "homepage:${Homepage}\\n" \
          "status:${db:Status-Abbrev}\\n" \
          "======\\n" \
          "description:${Description}\\n" \
          "------\\n'"
    cmd += ' {0}'.format(' '.join(packages))
    cmd = cmd.strip()

    call = __salt__['cmd.run_all'](cmd, python_chell=False)
    if call['retcode']:
        if failhard:
            raise CommandExecutionError("Error getting packages information: {0}".format(call['stderr']))
        else:
            return ret

    for pkg_info in [elm for elm in re.split(r"------", call['stdout']) if elm.strip()]:
        pkg_data = {}
        pkg_info, pkg_descr = re.split(r"======", pkg_info)
        for pkg_info_line in [el.strip() for el in pkg_info.split(os.linesep) if el.strip()]:
            key, value = pkg_info_line.split(":", 1)
            if value:
                pkg_data[key] = value
        install_date, install_date_t = _get_pkg_install_time(pkg_data.get('package'), pkg_data.get('arch'))
        if install_date:
            pkg_data['install_date'] = install_date
            pkg_data['install_date_time_t'] = install_date_t  # Unix ticks
        build_date, build_date_t = _get_pkg_build_time(pkg_data.get('package'))
        if build_date:
            pkg_data['build_date'] = build_date
            pkg_data['build_date_time_t'] = build_date_t
        pkg_data['description'] = pkg_descr.split(":", 1)[-1]
        ret.append(pkg_data)

    return ret
276779
def _find_pkg_info(self):
        
        dist = pkg_resources.require(self.package_name)[0]
        self._pkg_resources_locations = [dist.location]
        ver, url = self._dist_version_url(dist)
        return {'version': ver, 'url': url}