From 60859570860deb170632ac9825760233f67eca0b Mon Sep 17 00:00:00 2001 From: "xuanyi.wang" Date: Wed, 19 Apr 2023 04:38:34 +0200 Subject: [PATCH] Update page 'Day 9 homework - Sloetjes' --- Day 9 homework - Sloetjes.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Day 9 homework - Sloetjes.md b/Day 9 homework - Sloetjes.md index dc66076..606cf78 100644 --- a/Day 9 homework - Sloetjes.md +++ b/Day 9 homework - Sloetjes.md @@ -1,4 +1,4 @@ -1. Use `importlib.util.find_spec` to create a function that takes a Python module or package name, and returns the total number of bytes in the cached `.pyc` file, or the total number of bytes in the `.py` file if there is no cached bytecode. You can use the os.stat command to get the size of a file. +**1. Use `importlib.util.find_spec` to create a function that takes a Python module or package name, and returns the total number of bytes in the cached `.pyc` file, or the total number of bytes in the `.py` file if there is no cached bytecode. You can use the os.stat command to get the size of a file.** ``` import importlib.util @@ -27,4 +27,20 @@ def get_module_size(module_name): else: filename = module_path return os.stat(filename).st_size +``` + +**2. Create another function that uses the last function to see how many bytes are in all the modules listed in sys.modules. +** +``` +def get_all_modules_size(): + total_size = 0 + for module_name, module in sys.modules.items(): + if not hasattr(module, '__file__'): + continue + module_path = get_module_path(module_name) + if module_path is not None: + module_size = get_module_size(module_name) + total_size += module_size + return total_size +print(get_all_modules_size()) ``` \ No newline at end of file