Pythonを用いて、実行環境のメモリおよびディスク容量を確認する方法をメモします。
はじめに
おはよう。@bioerrorlogです。
あるとき、Pythonを用いて実行環境のメモリおよびディスク容量を確認する必要に迫られました。
そのときに使ったやり方を備忘録に残します。
環境
OS: Linux (Amazon Linux 2)
Python 3.8
ディスク/メモリ容量を取得する
ディスク容量
ディスク容量を確認するには、以下のコードを実行します。
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') # 10の9乗をギガとする場合 # print(f'Total: {total / (10**9)} GB') # print(f'Used: {used / (10**9)} GB') # print(f'Free: {free / (10**9)} GB')
Pythonの標準ライブラリshutil
を用いて、ディスク容量を確認します。
shutil.disk_usage(path)
のpath
部分に任意のパスを与えることで、そのパス割り当てのディスク総量/使用済み容量/空き容量を取得できます。
※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.
メモリ容量
続いて物理メモリ容量を確認するには、以下のコードを実行します。
import os mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') print(f'Memory total: {mem_bytes / (2**30)} GiB') # 10の9乗をギガとする場合 # print(f'Memory total: {mem_bytes / (10**9)} GB')
メモリのページサイズos.sysconf('SC_PAGE_SIZE')
と、物理メモリのページ数os.sysconf('SC_PHYS_PAGES')
から、物理メモリの総容量が算出できます。
※Windows環境ではこのsysconf
メソッドは利用できないのでご注意ください。
おわりに
以上、Pythonでメモリおよびディスク容量を調べる方法を記しました。
ローカルの端末あるいは普通のサーバであれば、システム情報やターミナルからメモリ/ディスク容量を確認できるかと思います。 ただ、何かの事情でPythonの実行環境しか渡されない場合、Pythonからこれら情報を取得する必要がでてきます。
そうしたケースに参考にしていただければ幸いです。
[関連記事]
参考
macos - Get hard disk size in Python - Stack Overflow
linux - Get total physical memory in Python - Stack Overflow
shutil — High-level file operations — Python 3.9.6 documentation
os — Miscellaneous operating system interfaces — Python 3.9.6 documentation