# !/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("600x100")
# cpu用ラベル
Static1 = tk.Label(text=u'CPU:')
Static1.pack(side='left')
# CPUの取得した使用率を表示する
txtcpu = tk.Entry(width=20)
txtcpu.pack(side='left', padx=0)
# memory用ラベル
Static2 = tk.Label(text=u'memory:')
Static2.pack(side='left')
# memoryの取得した使用率を表示する
txtmem = tk.Entry(width=20)
txtmem.pack(side='left', padx=0)
# disk用ラベル
Static3 = tk.Label(text=u'disk:')
Static3.pack(side='left')
# diskの取得した使用率を表示する
txtdsk = tk.Entry(width=20)
txtdsk.pack(side='left', padx=0)
log = './cpumem.log'
def btn_click():
# テキストボックスをクリア
txtcpu.delete(0, tk.END)
txtmem.delete(0, tk.END)
txtdsk.delete(0, tk.END)
if os.path.exists(log):
# 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()
txtmem.insert(0, memory.percent)
# CPUの使用率を取得
cpu_percent = psu.cpu_percent(interval=1)
txtcpu.insert(0, cpu_percent)
# diskの使用率
disk_percent = psu.disk_usage(path='/').percent
txtdsk.insert(0, disk_percent)
# textboxの値を取得
cpulog = txtcpu.get()
memorylog = txtmem.get()
disklog = txtdsk.get()
# ログに出力するフォーマット(日付 時間 cpu使用率 メモリ使用率 disk使用率)
f.write(dt + " " + cpulog + " , " +
memorylog + " , " + disklog + "\n")
else:
# logファイルがない場合
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()
txtmem.insert(0, memory.percent)
# CPUの使用率を取得
cpu_percent = psu.cpu_percent(interval=1)
txtcpu.insert(0, cpu_percent)
# diskの使用率
disk_percent = psu.disk_usage(path='/').percent
txtdsk.insert(0, disk_percent)
# textboxの値を取得
cpulog = txtcpu.get()
memorylog = txtmem.get()
disklog = txtdsk.get()
# ログに出力するフォーマット(日付 時間 cpu使用率 メモリ使用率 disk使用率)
f.write(dt + " " + cpulog + " , " +
memorylog + " , " + disklog + "\n")
# ボタンの生成
Button = tk.Button(root, text='使用率取得', command=btn_click)
Button.pack(fill='x', side='left', padx=0)
root.mainloop()