This article explains how to check memory and disk space on your execution environment using Python.
Introduction
I recently needed to check memory and disk space on an execution environment using Python. Here's a note for future reference on how to do this.
# Working Environment OS: Linux (Amazon Linux 2) Python 3.8
Note: This article was translated from my original post.
Getting Disk and Memory Capacity
Disk Space
To check disk space, use the following code:
import shutil total, used, free = shutil.disk_usage('/') print(f'Total: {total / (2**30)} GiB') print(f'Used: {used / (2**30)} GiB') print(f'Free: {free / (2**30)} GiB') # If you want to use 10^9 as giga # print(f'Total: {total / (10**9)} GB') # print(f'Used: {used / (10**9)} GB') # print(f'Free: {free / (10**9)} GB')
This uses Python's standard library shutil to check disk space. By passing any path to the path parameter of shutil.disk_usage(path), you can retrieve the total disk capacity, used space, and free space for that path.
※From the documentation for shutil.disk_usage:
Return disk usage statistics about the given path as a named tuple with the attributes total, used and free, which are the amount of total, used and free space, in bytes. path may be a file or a directory.
Memory Capacity
To check physical memory capacity, use the following code:
import os mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') print(f'Memory total: {mem_bytes / (2**30)} GiB') # If you want to use 10^9 as giga # print(f'Memory total: {mem_bytes / (10**9)} GB')
You can calculate the total physical memory capacity by multiplying the memory page size os.sysconf('SC_PAGE_SIZE') by the number of physical memory pages os.sysconf('SC_PHYS_PAGES').
※Note that the sysconf method is not available on Windows.
Conclusion
That's how you can check memory and disk space using Python.
On a local machine or regular server, you can typically check memory and disk space through system information or the terminal. However, if you only have access to a Python execution environment for some reason, you'll need to retrieve this information from within Python.
I hope this is helpful in such cases.
[Related Articles]
https://en.bioerrorlog.work/entry/pygame-cellfor-resten.bioerrorlog.work