Created
March 14, 2024 20:34
-
-
Save n2nco/b6a97b302c20acc27df6910b8ce22231 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import subprocess | |
import sys | |
def get_size(start_path): | |
total_size = 0 | |
for dirpath, dirnames, filenames in os.walk(start_path): | |
for f in filenames: | |
fp = os.path.join(dirpath, f) | |
# skip if it is symbolic link | |
if not os.path.islink(fp): | |
total_size += os.path.getsize(fp) | |
return total_size | |
# Get the list of installed packages using pip freeze | |
installed_packages = subprocess.run([sys.executable, '-m', 'pip', 'freeze'], capture_output=True, text=True).stdout.splitlines() | |
for package in installed_packages: | |
package_name = package.split('==')[0] | |
# Use pip show to get the location of the package | |
package_info = subprocess.run([sys.executable, '-m', 'pip', 'show', package_name], capture_output=True, text=True).stdout | |
# Extract the location from the package info | |
for line in package_info.splitlines(): | |
if line.startswith("Location:"): | |
location = line.split(":")[1].strip() | |
package_path = os.path.join(location, package_name.replace('-', '_')) | |
# Check if the path exists, as some packages might use a different structure | |
if not os.path.exists(package_path): | |
continue | |
# Calculate the size of the package | |
size = get_size(package_path) | |
print(f"{package_name}: {size / 1024 / 1024:.2f} MB") | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment