Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import multiprocessing
- from tkinter import messagebox, Frame, Tk, PhotoImage, Label, Text
- from threading import Thread
- from ping3 import verbose_ping
- class NewProcessPingWindow(multiprocessing.Process):
- def __init__(self, logo_raw,
- window_size: dict, url,
- packages, interval,
- timeout, ttl,
- size, set_daemon=None):
- super().__init__(daemon=set_daemon)
- self.logo_raw = logo_raw
- self.url_label_shown = False
- self.exit_flag = False
- self.screen_width = window_size['width']
- self.screen_height = window_size['height']
- self._url = str(url) if url else 'google.com'
- self._packages = int(packages) if packages else 4
- self._interval = float(interval) if interval else 1
- self._timeout = float(timeout) if timeout else 4
- self._ttl = int(ttl) if ttl else 128
- self._size = int(size) if size else 32
- self.console_max_width = 0
- self.font_size = 18
- def toggle_widgets(self, mouse_btn):
- self.w.unbind('<Button-3>')
- self.w.unbind('<Button-1>')
- if mouse_btn == 'Button-3':
- if self.main_console_frame.winfo_viewable():
- self.main_console_frame.pack_forget()
- self.w.geometry(f'{self.screen_width}x{self.screen_height}')
- self.url_label.pack(expand=True, fill='both') if self.url_label_shown else None
- else:
- self.screen_width, self.screen_height = self.w.winfo_width(), self.w.winfo_height()
- self.url_label.pack_forget()
- self.w.geometry('')
- self.main_console_frame.pack(fill='both', expand=True, side='top', anchor='n')
- elif mouse_btn == 'Button-1' and not self.main_console_frame.winfo_viewable():
- if self.url_label_shown:
- self.url_label.pack_forget()
- self.url_label_shown = False
- else:
- self.url_label.pack(expand=True, fill='both')
- self.url_label_shown = True
- self.w.bind('<Button-3>', lambda x, arg='Button-3': self.toggle_widgets(arg))
- self.w.bind('<Button-1>', lambda x, arg='Button-1': self.toggle_widgets(arg))
- def on_closing(self):
- if not self.exit_flag:
- if messagebox.askyesno("Подумай", "Прервать Ping?"):
- if not self.exit_flag: # Duplicate in case of opening message box before changing exit_flag
- self.exit_flag = True
- self.calculate_statistics()
- if not self.main_console_frame.winfo_viewable():
- self.toggle_widgets('Button-3')
- else:
- self.w.destroy()
- def calculate_statistics(self):
- statistics = [f'\n\nСтатистика Ping для {self._url}:',
- f' Пакетов: отправлено = {self.sent}, получено = {self.received}, потеряно = {self.sent - self.received}',
- f' ({int((100 / self.sent * (self.sent - self.received)) + (0.5 if self.sent != self.received else 0))}% потерь)',
- f'Приблизительное время приема-передачи в мс:',
- f' Минимальное = {self.min_delay if self.min_delay != 100000 else 0}мс, Максимальное = {self.max_delay}мс, Среднее = {(int((self.average_delay / self.received) + 0.5)) if self.received != 0 else 0}мс']
- for _ in statistics:
- if self.console['width'] < len(_):
- self.console.configure(width=len(_))
- self.console.configure(state='normal')
- self.console.insert('end', _ + '\n')
- self.console.see('end')
- self.console.configure(state='disabled')
- def resize_font(self, event=None):
- # получаем размеры окна
- width = self.w.winfo_width()
- height = self.w.winfo_height()
- # вычисляем оптимальный размер шрифта
- a = int(height / 2)
- buff = len(self.url_label["text"])
- b = int(width / (buff if buff >= 7 else 7))
- new_font_size = min(a, b)
- if new_font_size != self.font_size:
- self.font_size = new_font_size
- self.url_label.config(font=("Arial", self.font_size))
- def run(self):
- self.w = Tk()
- self.w.config(bg='#2b2b2b')
- self.w.protocol("WM_DELETE_WINDOW", self.on_closing)
- self.w.title(self._url)
- self.w.pack_propagate(True)
- self.logo_icon = PhotoImage(data=self.logo_raw)
- self.w.iconphoto(False, self.logo_icon)
- self.w.minsize(width=200, height=50)
- self.w.geometry(f'{self.screen_width}x{self.screen_height}')
- self.w.bind('<Button-3>', lambda x, arg='Button-3': self.toggle_widgets(arg))
- self.w.bind('<Button-1>', lambda x, arg='Button-1': self.toggle_widgets(arg))
- self.url_label = Label(self.w, text=self._url,
- font=f'Arial {self.font_size}', fg='#D6ECFF', activeforeground='#90CDFF',
- background='#2b2b2b', activebackground='#2b2b2b', relief='flat', bd=0)
- self.url_label.bind("<Configure>", self.resize_font)
- self.main_console_frame = Frame(self.w, bg='#2b2b2b')
- self.console_frame_outline = Frame(self.main_console_frame, bg='#3c3f41')
- self.console_bg = Frame(self.console_frame_outline, bg='#2b2b2b')
- self.console_title_frame = Frame(self.console_bg, bg='#3c3f41')
- self.console_address_frame = Frame(self.console_title_frame, bg='#3c3f41')
- self.address_l_0_0 = Label(self.console_address_frame, font='Consolas 14', bg='#3c3f41', fg='#90CDFF', text='Address:')
- self.address_l_0_1 = Label(self.console_address_frame, font='Consolas 14', bg='#3c3f41', fg='#D6ECFF', text=f'{self._url}')
- self.address_l_0_0.grid(row=0, column=0, sticky='e')
- self.address_l_0_1.grid(row=0, column=1, sticky='w')
- self.buff_line = Frame(self.console_title_frame, bg='#2b2b2b', height=2)
- self.console_info_frame = Frame(self.console_title_frame, bg='#3c3f41')
- self.info_l_0_0 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#90CDFF', text=f'Packages:')
- self.info_l_0_1 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#D6ECFF', text=f'{self._packages if self._packages > 0 else "∞"}')
- self.info_l_0_0.grid(row=0, column=0, sticky='e')
- self.info_l_0_1.grid(row=0, column=1, sticky='w')
- self.info_l_1_0 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#90CDFF', text=f'| Frequency:')
- self.info_l_1_1 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#D6ECFF', text=f'{self._interval}')
- self.info_l_1_0.grid(row=0, column=2, sticky='e')
- self.info_l_1_1.grid(row=0, column=3, sticky='w')
- self.info_l_2_0 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#90CDFF', text=f's | Timeout:')
- self.info_l_2_1 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#D6ECFF', text=f'{self._timeout}')
- self.info_l_2_0.grid(row=0, column=4, sticky='e')
- self.info_l_2_1.grid(row=0, column=5, sticky='w')
- self.info_l_3_0 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#90CDFF', text=f'bytes | TTL:')
- self.info_l_3_1 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#D6ECFF', text=f'{self._ttl}')
- self.info_l_3_0.grid(row=0, column=8, sticky='e')
- self.info_l_3_1.grid(row=0, column=9, sticky='w')
- self.info_l_4_0 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#90CDFF', text=f's | Size:')
- self.info_l_4_1 = Label(self.console_info_frame, font=f'Consolas 11', bg='#3c3f41', fg='#D6ECFF', text=f'{self._size}')
- self.info_l_4_0.grid(row=0, column=6, sticky='e')
- self.info_l_4_1.grid(row=0, column=7, sticky='w')
- self.console_frame = Frame(self.console_bg, bg='#2b2b2b')
- self.console = Text(self.console_frame, state='disabled',
- bg='#2b2b2b', fg='#D6ECFF', relief='flat',
- font=('Consolas', 11), height=20, width=30)
- self.console_frame_outline.pack(expand=True)
- self.console_bg.pack(expand=True, padx=2, pady=2)
- self.console_title_frame.pack(fill='both')
- self.console_address_frame.pack(fill='both', padx=5, pady=3)
- self.buff_line.pack(fill='both')
- self.console_info_frame.pack(side='left', padx=5, pady=6)
- self.console_frame.pack(fill='both')
- self.console.pack(side='left', padx=5, pady=5)
- Thread(target=self.ping, daemon=True, name='ping_thread').start()
- self.w.mainloop()
- def ping(self):
- last_response = None
- self.average_delay = 0
- self.max_delay = 0
- self.min_delay = 100000
- self.sent = 0
- self.received = 0
- for response in verbose_ping(dest_addr=self._url,
- count=self._packages,
- interval=self._interval,
- timeout=self._timeout,
- size=self._size,
- ttl=self._ttl):
- if self.console['width'] < len(response[1]):
- self.console.configure(width=len(response[1]))
- if not self.exit_flag:
- self.console.configure(state='normal')
- self.console.insert('end', response[1] + '\n')
- self.console.see('end')
- self.console.configure(state='disabled')
- else:
- break
- if response[0] != last_response:
- if not response[0]:
- self.w.config(bg='#ff0000')
- self.url_label.config(bg='#ff0000')
- elif response[0]:
- self.w.config(bg='#008000')
- self.url_label.config(bg='#008000')
- if response[0]:
- self.received += 1
- self.average_delay += response[2]
- if self.max_delay < response[2]:
- self.max_delay = response[2]
- if self.min_delay > response[2]:
- self.min_delay = response[2]
- last_response = response[0]
- self.sent += 1
- if self.exit_flag:
- break
- if not self.exit_flag:
- self.exit_flag = True
- self.calculate_statistics()
- # print('-----------------------------')
- # print(response)
- # print('current thread:', current_thread())
- # print('current PingObject:', self)
- # print('threads active:', active_count(), enumerate())
- # print('-----------------------------\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement