0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python勉強記録①

Posted at

pythonの勉強中で、作りたいものが無いためとりあえず
CPU使用率、memory使用率を取得しDBへ保存するプログラムを作成してみました。

目的

  • DBの学習
  • sqlalchemyの使い方
Package                   Version
------------------------- -----------
altair                    5.3.0
pip                       24.0
psutil                    6.0.0
pytz                      2024.1
SQLAlchemy                2.0.31
streamlit                 1.36.0
moniter.py
# pip install psutil
# pip install sqlalchemy
# pip install pytz

import psutil
import datetime
import pytz
import time
import os   
from sqlalchemy import create_engine, Column, Integer, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


Base = declarative_base()

class Moniter(Base):
    __tablename__ = 'moniter'
    id = Column(Integer, primary_key=True, autoincrement=True)
    # timestamp = Column(DateTime, default=datetime.datetime.now(pytz.timezone('Asia/Tokyo')))
    timestamp = Column(DateTime, default=lambda: datetime.datetime.now(pytz.timezone('Asia/Tokyo')).replace(microsecond=0))
    usage_percent = Column(Float)
    memory_usage = Column(Float)

    def __repr__(self):
        return f"Moniter(id={self.id}, timestamp={self.timestamp}, usage_percent={self.usage_percent}, memory_usage={self.memory_usage})"


# データベースファイルのパス
db_path = 'sqlite:///moniter.db'


# データベースファイルが存在しない場合のみ新しいデータベースを作成
if not os.path.exists('moniter.db'):
    # log無効
    engine = create_engine(db_path, echo=False)
    Base.metadata.create_all(engine)
else:
    engine = create_engine(db_path, echo=False)

Session = sessionmaker(bind=engine)
session = Session()

try:
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        memory_usage = psutil.virtual_memory().percent
        print(f"CPU Usage: {cpu_usage}%")
        print(f"Memory Usage: {memory_usage}%")
        print("-----------------")
        session.add(Moniter(usage_percent=cpu_usage, memory_usage=memory_usage))
        session.commit()
        time.sleep(60)
except KeyboardInterrupt:
    print("プログラムを終了します。")
finally:
    session.close()

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?