множество процессов после сборки скрипта auto-py-to-exe
Пишу программу пинга нескольких серверов, написал с помощью pysimplegui и собрал с помощью auto-py-to-exe - всё работает. Решил переписать на tkinter. В pycharm всё работает, но после сборки получаю множественные процессы Подскажите направление куда копать?
#!/usr/bin/env python3
import os
from tkinter import *
from tkinter import ttk
from time import sleep
from threading import Thread
import datetime
import subprocess
global thread_stop
def do_ping_in_loop(main_canvas,id):
fin_th = open('conf.txt', 'rt')
items_th = fin_th.readlines()
fin_th.close()
len_th = len(items_th)
mas_change = [1 for i in range(len_th)]
a = 1
while a == 1:
ii = 0
while ii < len_th:
if thread_stop:
return
response = subprocess.call("ping -n 1 " + items_th[ii], shell=True)
print(response)
if response != 0:
print(response)
# graph2 = windows.Element('graph'+str(ii))
current_date = datetime.date.today().isoformat()
current_time_date = datetime.datetime.today().isoformat()
if mas_change[ii]:
with open(items_th[ii].replace('.', '_').replace('\n', '') + '-' + str(current_date) + '.txt',
'a') as file:
file.write(f'{current_time_date} Сервер не доступен! \n')
mas_change[ii] = 0
main_canvas[ii].itemconfigure(id[ii], fill="red")
else:
# graph2 = windows.Element('graph'+str(ii))
current_date = datetime.date.today().isoformat()
current_time_date = datetime.datetime.today().isoformat()
if not mas_change[ii]:
with open(items_th[ii].replace('.', '_').replace('\n', '') + '-' + str(current_date) + '.txt',
'a') as file:
file.write(f'{current_time_date} Сервер доступен! \n')
mas_change[ii] = 1
main_canvas[ii].itemconfigure(id[ii], fill="green")
# graph.DrawImage(filename="foo.png", location=(0, 400))
# graph2.DrawRectangle((5, 5), (20, 20), line_color="green", fill_color='green')
ii += 1
sleep(1)
file_not_found=False
try:
fin = open('conf.txt', 'rt')
items = fin.readlines()
fin.close()
except FileNotFoundError:
file_not_found=True
root = Tk()
root.title("Тестовый пинг")
if not file_not_found:
len_ip=len(items)
max_len_of_items=0
for item in items:
if len(item)>max_len_of_items:
max_len_of_items=len(item)
win_width=max_len_of_items * 10 + 250
win_height=len_ip * 50
root.geometry(str(win_width)+"x"+str(win_height))
# max_len_of_items * 5 + 250, len_ip * 40
i=0
id_rectangle=[0 for i in range(len_ip)]
red = "red"
green = "green"
canvases = [Canvas(bg="white", width=20, height=20) for count in range(len_ip)]
while i < len_ip:
Label(text=items[i], font=("Arial", 14)).place(x=10, y=i*30+30)
# canvas = Canvas(bg="white", width=20, height=20)
canvases[i].place(x=max_len_of_items*20+30, y=i*30+30)
id_rectangle[i] = canvases[i].create_rectangle(0, 0, 200, 60, fill="red", outline="red")
i+=1
#label.place()
thread_stop=False
th = Thread(target=do_ping_in_loop, args=(canvases,id_rectangle),daemon=True)
th.start()
else:
count_label=0
text = ['Отсутствует файл conf.txt в папке с программой.',
'Добавьте файл и перезапустите программу',
'Синтаксис файла:',
'каждый сервер который необходимо',
'пинговать пишется с новой строки. Например:',
'ya.ru',
'172.25.48.97']
while count_label<7:
Label(text=text[count_label], font=("Arial", 14)).place(x=10, y=count_label*30+30)
count_label+=1
root.mainloop()
Ответы (1 шт):
Автор решения: user3216530
→ Ссылка
Всем спасибо!
Похоже, дело в определённой структуре проекта при работе с Tkinter и Threading.
Переписал всё вот так, и заработало:
import time
import threading
import tkinter as tk
from time import sleep
import datetime
import subprocess
class App(tk.Tk):
def __init__(self):
super().__init__()
file_not_found = False
try:
fin = open('conf.txt', 'rt')
items = fin.readlines()
fin.close()
except FileNotFoundError:
file_not_found = True
if not file_not_found:
len_ip = len(items)
max_len_of_items = 0
for item in items:
if len(item) > max_len_of_items:
max_len_of_items = len(item)
win_width = max_len_of_items * 10 + 250
win_height = len_ip * 50
self.geometry(str(win_width) + "x" + str(win_height))
# max_len_of_items * 5 + 250, len_ip * 40
i = 0
self.id_rectangle = [0 for i in range(len_ip)]
red = "red"
green = "green"
self.canvases = [tk.Canvas(bg="white", width=20, height=20) for count in range(len_ip)]
while i < len_ip:
tk.Label(text=items[i], font=("Arial", 14)).place(x=10, y=i * 30 + 30)
# canvas = Canvas(bg="white", width=20, height=20)
self.canvases[i].place(x=max_len_of_items * 20 + 30, y=i * 30 + 30)
self.id_rectangle[i] = self.canvases[i].create_rectangle(0, 0, 200, 60, fill="red", outline="red")
i += 1
# label.place()
thread_stop = False
# th = Thread(target=do_ping_in_loop, daemon=True)
# th.start()
# self.button = tk.Button(self, command=self.start_action,
# text="Ждать 5 секунд")
# self.button.pack(padx=50, pady=20)
thread = threading.Thread(target=self.run_action,daemon=True)
print(threading.main_thread().name)
print(thread.name)
thread.start()
def start_action(self):
self.button.config(state=tk.DISABLED)
#self.check_thread(thread)
def check_thread(self, thread):
if thread.is_alive():
self.after(100, lambda: self.check_thread(thread))
else:
self.button.config(state=tk.NORMAL)
def run_action(self):
fin_th = open('conf.txt', 'rt')
items_th = fin_th.readlines()
fin_th.close()
len_th = len(items_th)
mas_change = [1 for i in range(len_th)]
a = 1
while a == 1:
ii = 0
while ii < len_th:
# if thread_stop:
# return
response = subprocess.call("ping -n 1 " + items_th[ii], shell=True)
print(response)
if response != 0:
print(response)
# graph2 = windows.Element('graph'+str(ii))
current_date = datetime.date.today().isoformat()
current_time_date = datetime.datetime.today().isoformat()
if mas_change[ii]:
with open(items_th[ii].replace('.', '_').replace('\n', '') + '-' + str(current_date) + '.txt',
'a') as file:
file.write(f'{current_time_date} Сервер не доступен! \n')
mas_change[ii] = 0
self.canvases[ii].itemconfigure(self.id_rectangle[ii], fill="red")
else:
# graph2 = windows.Element('graph'+str(ii))
current_date = datetime.date.today().isoformat()
current_time_date = datetime.datetime.today().isoformat()
if not mas_change[ii]:
with open(items_th[ii].replace('.', '_').replace('\n', '') + '-' + str(current_date) + '.txt',
'a') as file:
file.write(f'{current_time_date} Сервер доступен! \n')
mas_change[ii] = 1
self.canvases[ii].itemconfigure(self.id_rectangle[ii], fill="green")
# graph.DrawImage(filename="foo.png", location=(0, 400))
# graph2.DrawRectangle((5, 5), (20, 20), line_color="green", fill_color='green')
ii += 1
sleep(1)
# print("Запуск длительного действия...")
# time.sleep(5)
# print("Длительное действие завершено!")
if __name__ == "__main__":
app = App()
app.mainloop()