pip安装twi包

2024-04-27 04:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

不幸的是,我无法复制它,但我们已经看过几次了:

pip installs one packages twice.

如果卸载第一个,第二个将可见,也可以卸载。在

我的问题是:如果一个包安装了两次,如何使用python进行检查?在

背景:我想写一个测试来检查这个(devOp)

更新

  • 软件包安装在virtualenv中。在
  • 这两个包有不同的版本。在
  • 这不是用手解决这个问题的解决方案的复制品。我用python代码搜索一个解决方案来检测这个问题。如何解决这不是我的问题的一部分。在

更新2

命令pip freeze只输出包一次:

pip freeze | grep -i south
South==0.8.1

但在虚拟环境中,它存在两次:

^{pr2}$

Tags: pip代码命令版本virtualenvpackages解决方案one
3条回答

这应该是有效的:

def count_installs(pkg_name):
    import imp, sys
    n = 0
    for location in sys.path:
        try:
            imp.find_module(pkg_name, [location])
        except ImportError: pass
        else: n += 1
    return n

例如

^{pr2}$

South-0.8.1-py2.7.egg是一个zip归档文件,其源代码为SouthSouth-0.8.4-py2.7.egg-info是一个包含South库的元数据文件的目录。在

.egg-info(对于从.tar.gz构建的库)或{}(对于从轮子.whl安装的lib)都存在于pip安装的每个库中。在

如果库在元数据中标记为zip_safe(在setup.pysetup(zip_safe=True)),则创建.egg存档。 否则,pip用提取的python源文件创建一个目录。在

非常旧的setuptools版本能够安装同一个库的多个版本,并将其中一个标记为active,但如果我没记错的话,提到的功能多年前就被删除了。在

我使用此方法检查包是否安装了两次:

def test_pip_python_packages_installed_twice(self):
    # https://stackoverflow.com/a/23941861/633961
    pkg_name_to_locations=defaultdict(set)
    for dist in pkg_resources.working_set:
        for pkg_name in dist._get_metadata('top_level.txt'):
            for location in sys.path:
                try:
                    importutils.does_module_exist_at_given_path(pkg_name, [location])
                except ImportError:
                    continue
                if location.startswith('/usr'):
                    # ignore packages from "root" level.
                    continue
                pkg_name_to_locations[pkg_name].add(location)

    errors=dict()
    for pkg_name, locations in sorted(pkg_name_to_locations.items()):
        if pkg_name in ['_markerlib', 'pkg_resources', 'site', 'easy_install', 'setuptools', 'pip']:
            continue
        if len(locations)==1:
            continue
        errors[pkg_name]=locations
    self.assertFalse(errors, 
                     'Some modules are installed twice:\n%s' % '\n'.join(['%s: %s' % (key, value) for key, value in sorted(errors.items())]))

重要

^{pr2}$

相关:imp.find_module() which supports zipped eggs

相关问题 更多 >