如何打印导入库的大小?

问题描述

反正有没有用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'))