process_monitor.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import psutil
  2. from datetime import datetime
  3. import pandas as pd
  4. import time
  5. import os
  6. def get_size(bytes):
  7. """Returns size of bytes in a nice format"""
  8. for unit in ['', 'K', 'M', 'G', 'T', 'P']:
  9. if bytes < 1024:
  10. return f"{bytes:.2f}{unit}B"
  11. bytes /= 1024
  12. def get_processes_info(name_filter):
  13. processes = []
  14. for process in psutil.process_iter():
  15. with process.oneshot():
  16. pid = process.pid
  17. if pid == 0:
  18. continue
  19. name = process.name().lower()
  20. if name not in name_filter:
  21. continue
  22. try:
  23. create_time = datetime.fromtimestamp(process.create_time())
  24. except OSError:
  25. create_time = datetime.fromtimestamp(psutil.boot_time())
  26. try:
  27. cores = len(process.cpu_affinity())
  28. except psutil.AccessDenied:
  29. cores = 0
  30. cpu_usage = process.cpu_percent()
  31. status = process.status()
  32. try:
  33. nice = int(process.nice())
  34. except psutil.AccessDenied:
  35. nice = 0
  36. try:
  37. memory_usage = process.memory_full_info().uss
  38. except psutil.AccessDenied:
  39. memory_usage = 0
  40. io_counters = process.io_counters()
  41. read_bytes = io_counters.read_bytes
  42. write_bytes = io_counters.write_bytes
  43. n_threads = process.num_threads()
  44. try:
  45. username = process.username()
  46. except psutil.AccessDenied:
  47. username = "N/A"
  48. processes.append({
  49. 'pid': pid, 'name': name, 'create_time': create_time,
  50. 'cores': cores, 'cpu_usage': cpu_usage, 'status': status, 'nice': nice,
  51. 'memory_usage': memory_usage, 'read_bytes': read_bytes, 'write_bytes': write_bytes,
  52. 'n_threads': n_threads, 'username': username,
  53. })
  54. return processes
  55. def construct_dataframe(processes):
  56. df = pd.DataFrame(processes)
  57. df.set_index('pid', inplace=True)
  58. df.sort_values(sort_by, inplace=True)
  59. # pretty printing bytes
  60. df['memory_usage'] = df['memory_usage'].apply(get_size)
  61. df['write_bytes'] = df['write_bytes'].apply(get_size)
  62. df['read_bytes'] = df['read_bytes'].apply(get_size)
  63. # convert to proper date format
  64. df['create_time'] = df['create_time'].apply(datetime.strftime, args=("%Y-%m-%d %H:%M:%S",))
  65. # reorder and define used columns
  66. df = df[columns]
  67. return df
  68. if __name__ == "__main__":
  69. sort_by = "memory_usage"
  70. columns = ["name", "cpu_usage", "memory_usage", "read_bytes", "write_bytes",
  71. "status", "create_time", "nice", "n_threads", "cores", "username"]
  72. name_filter = ["pwrplay.exe", "httpd.exe", "impadmin.exe", "trnsfrmr.exe"]
  73. while True:
  74. processes = get_processes_info(name_filter)
  75. if len(processes) > 0:
  76. df = construct_dataframe(processes)
  77. os.system("cls") if "nt" in os.name else os.system("clear")
  78. print(df.to_string())
  79. else:
  80. print('No active processes.')
  81. time.sleep(10)