LoginSignup
1
3

More than 3 years have passed since last update.

【第1回】pythonでCPUとメモリの使用率を取得する

Posted at

作成環境

スクリーンショット 2020-01-03 15.01.16.png
スクリーンショット 2020-01-03 15.03.40.png

pythonで何か作りたい。

  • CPU使用率とメモリ使用率を取得したい。
  • どうせならGUIで作りたい。
  • ボタンを押したときに取得したい。

プログラムを組み上げる前に考慮すること

  • CPUとかメモリとかだからOSに依存するでしょ。→import sysが必要だな。
  • CPUとかメモリ→import psutilも必要だな。
  • GUIにしたいから→import tkinterを使おう。(多分他の方法でもできる)
  • CPUの表示とメモリの表示であることのラベルが必要だな。
  • 取得のきっかけになるボタンがいる。
  • ボタンを押したときに値を表示するBOXがいる。

実際のソース

#!/usr/bin/env python
import psutil as psu
import tkinter as tk
import sys

# tkinterでwindowの作成とタイトルを作る
# windowサイズの指定
root = tk.Tk()
root.title(u"CPU&メモリ使用率")
root.geometry("600x300")

# cpu用ラベル
Static1 = tk.Label(text=u'CPU:')
Static1.pack()
# CPUの取得した値を表示する
txtcpu = tk.Entry(width=20)
txtcpu.pack()

# memory用ラベル
Static2 = tk.Label(text=u'memory:')
Static2.pack()

# memoryの取得した値を表示する
txtmem = tk.Entry(width=20)
txtmem.pack()


def btn_click():
    # テキストボックスをクリア
    txtcpu.delete(0, tk.END)
    txtmem.delete(0, tk.END)
    # メモリの利用情報を取得
    memory = psu.virtual_memory()
    txtcpu.insert(0, memory.percent)
    # debug_cpu使用率をTerminalに表示
    #print('メモリ使用率:', memory.percent)

    cpu_percent = psu.cpu_percent(interval=1)
    txtmem.insert(0, cpu_percent)
    # debug_memory用の使用率をTerminalに表示
    #print('CPU使用率:', cpu_percent)


# ボタンの生成
Button = tk.Button(root, text='使用率取得', command=btn_click)
Button.pack()

root.mainloop()

考慮不足であとから直しながら追加したもの

  • テキストボックスをクリアをしないと数字がどんどん連ねられてわけがわからなくなるのでボタンが押されたら値をクリアする。

まだ進化させたいことがあるので今回は第1回とします。

  • 現時点でやりたいことが2つくらいあるので次回また進化版の記事を書く予定です。
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3