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