如何打印导入库的大小?

How to print size of an imported library?

有没有办法在python中打印出库的大小?这个方法我试过了,还是不行:

>>> import sys
>>> import fastai as fastai
>>> import pytorch as torch

>>> print(sys.getsizeof(torch))
88
>>> print(sys.getsizeof(fastai))
88

我认为 fastai 约为 1.9 MB,pytorch 约为 320 MB,但我想确认一下。

试试这个

import os, sys
dir_size = lambda dirpath:sum([(sum([os.path.getsize(os.path.join(root, f)) for f in files]) + sum([dir_size(os.path.join(root, d)) for d in dirs])) for root, files, dirs in os.walk(dirpath)])
def module_size(module_name):
    for p in sys.path:
        if os.path.exists(os.path.join(p, module_name)+'.py'):
            return f"{os.path.getsize(os.path.join(p, module_name)+'.py')/1024.0} KB"
        if os.path.exists(os.path.join(p, module_name)):            
            return f'{dir_size(os.path.join(p, module_name))/1024.0} KB'
    return 'Module not installed.'

print(module_size('fastai'))
print(module_size('pytorch'))