Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.65 KB | None | 0 0
  1. import psutil
  2. import os
  3. import time, csv
  4. import platform, cpuinfo, re
  5. import subprocess
  6. import termcolor
  7. from datetime import datetime, timedelta
  8.  
  9. def monitoring_go_eng():
  10. print('------------------------------------------')
  11. print('INFO_System:')
  12. print('OS:'+' '+str(platform.platform()))
  13. print('RAM total:' + ' ' + str((psutil.virtual_memory().total ) / (1024 * 1024 * 1024)) + ' ' + 'Gb')
  14. print('Brand CPU:'+' '+str(cpuinfo.get_cpu_info()['brand']))
  15. print('Count CPU:'+' '+str(psutil.cpu_count()))
  16. print('------------------------------------------')
  17. data_monitoring=[['Time','Temperature CPU (С)','Load CPU (%)', 'Used RAM (Gb)']]
  18.  
  19.  
  20. min=input('enter time measurement in minutes and press the button "Enter": ').replace(',', '.')
  21. start = datetime.now()
  22. file_date_time = str(time.strftime("%Y-%m-%d_%H-%M-%S"))
  23. sys_data=['Measurement date:'+' '+file_date_time,'OS:'+' '+str(platform.platform()), 'Brand CPU:'+' '+str(cpuinfo.get_cpu_info()['brand']), 'Count CPU:'+' '+str(psutil.cpu_count()), 'RAM total:'+' '+str((psutil.virtual_memory().total) / (1024*1024*1024))+' ' + 'Gb','Measurement data']
  24.  
  25.  
  26. def type_corr(min=0): # input validation function, returns a Boolean value
  27. if re.search(r'^[-+]?[0-9]*[.,]?[0-9]+(?:[eE][-+]?[0-9]+)?$', min) is not None: return True
  28. else: return False
  29.  
  30.  
  31. while type_corr(min)==False:
  32. min = input('enter time measurement in minutes and press the button "Enter": ').replace(',', '.')
  33.  
  34.  
  35. def get_os_info(): # get name OS
  36. os_info = str(platform.uname().system) # name OS
  37. return os_info # return name OS
  38.  
  39.  
  40. def get_temperature_info_windows(data_monitoring): # a function of production data if ОS windows
  41. import wmi
  42. import colorama
  43. colorama.init()
  44. w = wmi.WMI(namespace="root\wmi")
  45. data_itermonitoring=[] # the list of data for save
  46. temperature_info = w.MSAcpi_ThermalZoneTemperature()[0] # getting the total CPU temperature
  47. temperature_info = round(((temperature_info.CurrentTemperature / 10) - 273), 4) # the translation to Celsius
  48. cpu_proc1 = str(psutil.cpu_percent()) # load CPU
  49. cpu_proc2 = int(cpu_proc1[:cpu_proc1.find('.')]) # load CPU for progress-bar
  50. termcolor.cprint('|'+'Temperature CPU= ' + str(temperature_info) + ' ' + 'C', 'red') # the output of temperature into the terminal
  51. termcolor.cprint('|'+sym * round(temperature_info) + '|','red') #the output of progress-bar
  52. termcolor.cprint('|'+'Load CPU=' + str(cpu_proc1) + ' '+'%', 'green') # the output of load CPU into the terminal
  53. termcolor.cprint('|'+sym * cpu_proc2 + '|', 'green') #the output of progress-bar
  54. termcolor.cprint('|'+'Used RAM=' + str((psutil.virtual_memory().used) / (1024*1024*1024)) + ' ' + 'Gb', 'yellow') # the output of RAM uses into the terminal
  55. termcolor.cprint('|'+sym * round((psutil.virtual_memory().used) / (1024 * 1024 * 1024)) + '|', 'yellow') #the output of progress-bar
  56. data_itermonitoring.append((time.strftime("%H:%M:%S")))
  57. data_itermonitoring.append(str(temperature_info))
  58. data_itermonitoring.append(str(cpu_proc1))
  59. data_itermonitoring.append(str((psutil.virtual_memory().used) / (1024*1024*1024)))
  60. data_monitoring.append(data_itermonitoring)
  61. time.sleep(2)
  62. os.system('cls') # clear terminal
  63.  
  64. def get_temperature_info_linux(data_monitoring): # a function of production data if ОS linux
  65. from termcolor import cprint
  66. data_itermonitoring = [] # the list of data for save
  67. temperature_info = [] # the list of temperature for each CPU core
  68. for i in range(0, len(psutil.sensors_temperatures()['coretemp'])):
  69. temperature_info.append(psutil.sensors_temperatures()['coretemp'][i][1]) # temperature of each CPU core
  70. temperature_info = float((sum(temperature_info)) / (len(psutil.sensors_temperatures()['coretemp']))) # arithmetic mean of temperature CPU
  71. cpu_proc1 = str(psutil.cpu_percent()) # load CPU
  72. cpu_proc2 = int(cpu_proc1[:cpu_proc1.find('.')]) # load CPU for progress-bar
  73. termcolor.cprint('|'+'Temperature CPU=' + str(temperature_info) + ' ' + 'C', 'red') # the output of temperature into the terminal
  74. termcolor.cprint('|'+sym * round(temperature_info) + '|' ,'red') #the output of progress-bar
  75. termcolor.cprint('|'+'Load CPU=' + str(cpu_proc1) + ' '+'%', 'green') # the output of load CPU into the terminal
  76. termcolor.cprint('|'+sym * cpu_proc2 + '|', 'green') #the output of progress-bar
  77. termcolor.cprint('|'+'Used RAM=' + str((psutil.virtual_memory().used) / (1024*1024*1024)) + ' ' + 'Gb', 'yellow') # the output of RAM uses into the terminal
  78. termcolor.cprint('|'+sym * round((psutil.virtual_memory().used) / (1024 * 1024 * 1024)) + '|', 'yellow') #the output of progress-bar
  79. data_itermonitoring.append((time.strftime("%H:%M:%S")))
  80. data_itermonitoring.append(str(temperature_info))
  81. data_itermonitoring.append(str(cpu_proc1))
  82. data_itermonitoring.append(str((psutil.virtual_memory().used) / (1024 * 1024 * 1024)))
  83. data_monitoring.append(data_itermonitoring)
  84. time.sleep(2)
  85. os.system('clear') # clear terminal
  86.  
  87.  
  88. while datetime.now() - start <= timedelta(seconds=float(min)*60): # make out the specified time in minutes
  89. if get_os_info() == 'Windows': get_temperature_info_windows(data_monitoring) # function call for Windows
  90. elif get_os_info() == 'Linux': get_temperature_info_linux(data_monitoring) # function call for Linux
  91. else:
  92. print("Stop: Doesn't suit for ОS")
  93. break
  94.  
  95.  
  96. def save_monitoring(data_monitoring): # to save monitoring data
  97. with open(f'measurement_data_{file_date_time}.csv', 'w') as resultFile:
  98. wr = csv.writer(resultFile, delimiter =';')
  99. for item in sys_data:
  100. wr.writerow([item])
  101. wr.writerows(data_monitoring)
  102.  
  103. def quest_save():
  104. quest_s = input('Do you want to save monitoring data [yes/no]: ').lower()
  105. if quest_s.lower()=="yes":return True
  106. else: return False
  107.  
  108. while True:
  109. if quest_save()==True:
  110. save_monitoring(data_monitoring)
  111. break
  112. else: break
  113.  
  114.  
  115. def monitoring_go_rus():
  116. print('------------------------------------------')
  117. print('ИНФОРМАЦИЯ О СИСТЕМЕ:')
  118. print('OC:' + ' ' + str(platform.platform()))
  119. print('Доступная физическая оперативная память:' + ' ' + str((psutil.virtual_memory().total) / (1024 * 1024 * 1024)) + ' ' + 'Gb')
  120. print('Марка ЦП:' + ' ' + str(cpuinfo.get_cpu_info()['brand']))
  121. print('Количество ядер:' + ' ' + str(psutil.cpu_count()))
  122. print('------------------------------------------')
  123. data_monitoring = [['Время', 'Температура ЦП (С)', 'Загрузка ЦП (%)', 'Использование ОЗУ (Гб)']]
  124. min = input('введите время выволения мониторинга в минутах и нажмите "Enter": ').replace(',', '.')
  125. start = datetime.now()
  126. file_date_time = str(time.strftime("%Y-%m-%d_%H-%M-%S"))
  127. sys_data = ['Дата измеренеий:'+' '+str(time.strftime("%Y-%m-%d %H:%M:%S")), 'ОС:' + ' ' + str(platform.platform()),'Марка ЦП:' + ' ' + str(cpuinfo.get_cpu_info()['brand']), 'Количество ядер:' + ' ' + str(psutil.cpu_count()),'Доступная физическая оперативная память:' + ' ' + str((psutil.virtual_memory().total) / (1024 * 1024 * 1024)) + ' ' + 'Гб','Таблица измерений:']
  128.  
  129. def type_corr(min=0): # фукнция проверки правильности ввода, возвращет логическое значение
  130. if re.search(r'^[-+]?[0-9]*[.,]?[0-9]+(?:[eE][-+]?[0-9]+)?$', min) is not None:
  131. return True
  132. else:
  133. return False
  134.  
  135. while type_corr(min) == False: # ввод времени мониторинга в минутах, возможно вводить десятичные дроби
  136. min = input('введите время выволения мониторинга в минутах и нажмите "Enter": ').replace(',', '.')
  137.  
  138. def get_os_info(): # получить название ОС
  139. os_info = str(platform.uname().system) # имя ОС
  140. return os_info # вернуть название ОС
  141.  
  142. def get_temperature_info_windows(data_monitoring): # функция получения данных если ОС windows
  143. import wmi
  144. import colorama
  145. colorama.init()
  146. w = wmi.WMI(namespace="root\wmi")
  147. data_itermonitoring = [] #список для хранения данных измерений
  148.  
  149. temperature_info = w.MSAcpi_ThermalZoneTemperature()[0] # получение общей температуры процессора
  150. temperature_info = round(((temperature_info.CurrentTemperature / 10) - 273), 4) # перевод в градусы C
  151. cpu_proc1 = str(psutil.cpu_percent()) # загрузка ЦП для вывода
  152. cpu_proc2 = int(cpu_proc1[:cpu_proc1.find('.')]) # загрузка ЦП для умножения строки и показания прогресс бара
  153. termcolor.cprint('|'+'температура ЦП=' + str(temperature_info) + ' ' + 'C','red') # вывод температуры в терминал
  154. termcolor.cprint('|'+sym * round(temperature_info) + '|','red')
  155. termcolor.cprint('|'+'загрузка ЦП=' + str(cpu_proc1) + ' '+'%','green') # вывод загрузки ЦП в терминал
  156. termcolor.cprint('|'+sym * cpu_proc2 + '|', 'green')
  157. termcolor.cprint('|'+'ОЗУ=' + str((psutil.virtual_memory().used) / (1024 * 1024 * 1024)) + ' ' + 'Gb', 'yellow')
  158. termcolor.cprint('|'+sym * round((psutil.virtual_memory().used) / (1024*1024*1024)) + '|', 'yellow') # вывод используемой памяти в терминал
  159. data_itermonitoring.append((time.strftime("%H:%M:%S")))
  160. data_itermonitoring.append(str(temperature_info))
  161. data_itermonitoring.append(str(cpu_proc1))
  162. data_itermonitoring.append(str((psutil.virtual_memory().used) / (1024*1024*1024)))
  163. data_monitoring.append(data_itermonitoring)
  164. time.sleep(2)
  165. os.system('cls') # очистка терминала
  166.  
  167. def get_temperature_info_linux(data_monitoring): # функция получения данных если ОС linux
  168. from termcolor import cprint
  169. data_itermonitoring = []
  170. temperature_info = [] # список в который заноcится температура по ядрам
  171. for i in range(0, len(psutil.sensors_temperatures()['coretemp'])):
  172. temperature_info.append(psutil.sensors_temperatures()['coretemp'][i][1]) # получение температуры по ядрам
  173. temperature_info = float((sum(temperature_info)) / (len(psutil.sensors_temperatures()['coretemp']))) # подсчет среднего значения температуры
  174. cpu_proc1 = str(psutil.cpu_percent()) # загрузка ЦП для вывода
  175. cpu_proc2 = int(cpu_proc1[:cpu_proc1.find('.')]) # загрузка ЦП для умножения строки и показания прогресс бара
  176. termcolor.cprint('|'+'температура ЦП=' + str(temperature_info) + ' ' + 'C','red') # вывод температуры в терминал
  177. termcolor.cprint('|'+sym * round(temperature_info) + '|','red')
  178. termcolor.cprint('|'+'загрузка ЦП=' + str(cpu_proc1) +' '+'%','green') # вывод загрузки ЦП в терминал
  179. termcolor.cprint('|'+sym * cpu_proc2 + '|', 'green')
  180. termcolor.cprint('|'+'ОЗУ=' + str((psutil.virtual_memory().used) / (1024*1024*1024)) + ' ' + 'Gb', 'yellow') # вывод используемой памяти в терминал
  181. termcolor.cprint('|'+sym * round((psutil.virtual_memory().used) / (1024 * 1024 * 1024))+'|', 'yellow')
  182. data_itermonitoring.append((time.strftime("%H:%M:%S")))
  183. data_itermonitoring.append(str(temperature_info))
  184. data_itermonitoring.append(str(cpu_proc1))
  185. data_itermonitoring.append(str((psutil.virtual_memory().used) / (1024 * 1024 * 1024)))
  186. data_monitoring.append(data_itermonitoring)
  187. time.sleep(2)
  188. os.system('clear') # очистка терминала
  189.  
  190. while datetime.now() - start <= timedelta(seconds=float(min) * 60): # выполнять заданное время в минутах
  191. if get_os_info() == 'Windows': get_temperature_info_windows(data_monitoring) # вывзов функции для Windows
  192. elif get_os_info() == 'Linux': get_temperature_info_linux(data_monitoring) # вывзов функции для Linux
  193. else:
  194. print('Стоп: Программа не подходит для данной ОС')
  195. break
  196.  
  197. def save_monitoring(data_monitoring):
  198. with open(f'данные_мониторинга_{file_date_time}.csv', 'w') as resultFile:
  199. wr = csv.writer(resultFile, delimiter=';')
  200. for item in sys_data:
  201. wr.writerow([item])
  202. wr.writerows(data_monitoring)
  203.  
  204. def quest_save():
  205. quest_s = input('сохранить данные мониторинга [да/нет]: ').lower()
  206. if quest_s.lower() == "да":
  207. return True
  208. else: return False
  209.  
  210. while True:
  211. if quest_save() == True:
  212. save_monitoring(data_monitoring)
  213. break
  214. else: break
  215.  
  216. def select_your_language(): # a function for enter your language/функция ввода языкка
  217. language=input('enter your language/введите язык [rus/eng]: ').lower()
  218. print('------------------------------------------')
  219. return language
  220.  
  221. lang=select_your_language()
  222.  
  223.  
  224. def soft_info_rus():
  225. rus_info=['Разработчик: Алексей Сурнов', 'RAM-CPU-temp служит для контроля в реальном времени за параметрами:', '--температуры процессора'
  226. , '--задействованной оперативной памяти', '--загрузки процессора',
  227. 'Вы можете сохранить результаты в отдельный файл после выполнения измерений.',
  228. 'Файл с данными в формате csv будет находится в той же папке что и программа',
  229. 'Использовать в операционных системаx: ', '--Windows v.7,8,10 ', '--Linux Debian, Linux Mint, Linux Ubuntu.']
  230. for info in rus_info:
  231. print(info)
  232. print('------------------------------------------')
  233.  
  234.  
  235.  
  236. def soft_info_eng():
  237. eng_info=['Developer: Alexey Surnov', 'RAM-CPU-temp serves for real-time monitoring of parameters:', '--СPU temperature'
  238. , '--involved RAM', '--CPU load',
  239. 'You can save the results in a separate file after taking measurements.',
  240. 'The data file in csv format will be located in the same folder as the program',
  241. 'Use in operating systems: ', '--Windows v.7,8,10 ', '--Linux Debian, Linux Mint, Linux Ubuntu.']
  242. for info in eng_info:
  243. print(info)
  244. print('------------------------------------------')
  245.  
  246.  
  247. if lang=='rus': soft_info_rus()
  248. elif lang=='eng': soft_info_eng()
  249. sym = '▌' # символ прогресс бара/a symbol of the progress bar
  250.  
  251. while True:
  252. if lang=='rus':
  253. flag = input('Начать выполнение мониторинга [да/нет]: ')
  254. if flag == 'да': monitoring_go_rus()
  255. elif flag=='нет':
  256. input('Для выхода нажмите Enter')
  257. break
  258. else:
  259. print('неправильный ввод'+' '+'вы ввели:'+ ' '+'|'+flag+'|'+' '+ 'повторите попытку')
  260. print('введите [да/нет]')
  261. elif lang=='eng':
  262. flag = input('Do you want to start monitoring [yes/no]: ')
  263. if flag == 'yes': monitoring_go_eng()
  264. elif flag=='no':
  265. input('To exit the program press the button "Enter"')
  266. break
  267. else:
  268. print('invalid input'+' '+'you made:'+' '+'|'+flag+'|'+' '+ 'please try again')
  269. print('enter [yes/no]')
  270. else:
  271. print('invalid input, please try again / неправильный ввод языка, повторите попытку')
  272. lang = select_your_language()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement