1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2020-01-13

CPUとメモリの使用率を取得する第2回です。

前回からの違いは、ボタンを押した分だけログが取れること

動くこと優先してます。

  • ソース的にキレイにできそうなところもあるけどとりあえず動くことを優先してます。

ファイルの存在確認入れてるんだけど?

  • なんかうまく動いてないっぽい。
  • logファイルを先に作っておくとうまくいく。

動作確認

  • windows10 1909
  • mac catalina
# !/usr/bin/env python
import psutil as psu
import tkinter as tk
import sys
import os
import datetime

# 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()


log = './cpumem.log'


def btn_click():
    # テキストボックスをクリア
    txtcpu.delete(0, tk.END)
    txtmem.delete(0, tk.END)
    if(os.path.exists(log)):
        with open(log, mode='a', encoding="utf-8") as f:
            # 時間の取得
            dt_now = datetime.datetime.now()
            # 日時のフォーマット修正
            dt = dt_now.strftime('%Y/%m/%d %H:%M:%S')
            # メモリの利用情報を取得
            memory = psu.virtual_memory()
            txtcpu.insert(0, memory.percent)
            cpu_percent = psu.cpu_percent(interval=1)
            txtmem.insert(0, cpu_percent)
            cpulog = txtcpu.get()
            memorylog = txtmem.get()
            f.write(dt + " " + cpulog + " , " + memorylog + "\n")
    else:
        with open(log, mode='w', encoding="utf-8") as f:
            # 時間の取得
            dt_now = datetime.datetime.now()
            # 日時のフォーマット修正
            dt = dt_now.strftime('%Y/%m/%d %H:%M:%S')
            # メモリの利用情報を取得
            memory = psu.virtual_memory()
            txtcpu.insert(0, memory.percent)
            cpu_percent = psu.cpu_percent(interval=1)
            txtmem.insert(0, cpu_percent)
            cpulog = txtcpu.get()
            memorylog = txtmem.get()
            f.write(dt + " " + cpulog + " , " + memorylog + "\n")


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

root.mainloop()

実は、まだ次回があります。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?