【问题标题】:How to know size of python module?如何知道python模块的大小?
【发布时间】:2016-08-23 08:53:42
【问题描述】:

当我使用pip install module_name 安装模块时,我可以看到轮子或包的大小。

所以问题是,是否可以只知道每个模块的大小?

类似的东西。

import pip

for dist in pip.get_installed_distributions():
    print(distribution_size_only of dist)

我想知道分布的估计大小,以便我可以从 winpython 分布中删除它们。

【问题讨论】:

  • 定义“尺寸”。 pip 显示下载时压缩存档的大小。安装大小将与此大不相同,这取决于那里是否有已编译的扩展,或者是否包含易于压缩的数据文件等。
  • 无论如何,安装后分发大小不会存储为元数据,您必须查询原始下载位置以获取该版本的存档大小。
  • 另外,依赖项呢?这些应该包括在计算中吗?你在这里的最终目标是什么?计算必须下载多少才能重现当前设置?
  • 如果你想要estimated,那么你可以在我下面的脚本中找到它。估计不等于 1:1 大小对吧?

标签: python


【解决方案1】:
import os
import pip


def calc_container(path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size


for dist in pip.get_installed_distributions():
    try:
        path = os.path.join(dist.location, dist.project_name)
        size = calc_container(path)
        if size:
            print path
            print size
    except OSError:
        '{} no longer exists'.format(dist.project_name)

如果你在 virtualenv 中,你可以使用第一个选项来获得更多:

get_installed_distributions(local_only=True, skip=('python', 'wsgiref', 'argparse'), include_editables=True, editables_only=False, user_only=False) 返回已安装 Distribution 对象的列表。

如果 local_only 为 True(默认),则仅返回安装 当前 virtualenv 的本地,如果在 virtualenv 中。

【讨论】:

  • 这会计算安装的大小(但忽略任何已安装的脚本或数据文件)。我认为 OP 想要获得分布大小(示例代码中的distribution_size_only)。
  • @MartijnPieters 谁知道。也许是的,让我们等待 Scripting.FileSystemObject 说明。无论如何,它可以完成,但不会那么快,因为如果我们正在考虑分发,那么我们还需要同时安装所有依赖项,如果他对将要安装的内容有全局视图。但是如您所知,我们可以将整个模块复制并粘贴到我们的项目目录中并从中导入,它就可以工作了。我们不必安装它,python模块就是一个python模块。它只需要拥有所有依赖项。
  • 谢谢。我会调查的。
【解决方案2】:

我知道这很模糊,但这就是我想要的:

import re
import requests
import json
def regexsubstring(s, p):
    p = re.compile(p, flags=re.IGNORECASE)
    return p.search(s)

def wf(data,path,mode):
    with open(path, mode, encoding='utf-8') as out:
        out.write(data)
        return

import pip
dists_size_info = {}

for dist in pip.get_installed_distributions():
    url = "https://pypi.python.org/pypi/" + dist.key + "/" + dist.version
    r = requests.get(url)
    size = regexsubstring(r.text, """<td style="text-align: right;">(\w+)</td>""").group(1)
    dists_size_info[dist.key] = [dist.version, size]
    print(dists_size_info)
wf(json.dumps(dists_size_info),'dists_size_info.txt','w')

或者您可以在以下位置获取列表:

http://hastebin.com/qiconesoje.apache

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2015-08-07
    • 2014-09-09
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    相关资源
    最近更新 更多