Как завершить процесс наблюдения, если в приложении Python tkinter статус утилиты активен? ⇐ Python

Программы на Python
Anonymous
Как завершить процесс наблюдения, если в приложении Python tkinter статус утилиты активен?

Сообщение Anonymous »

У меня есть приложение tkinter Python, в котором я проверяю статус утилиты через API при вводе адреса электронной почты. Если статус утилиты активен, я хочу завершить процесс наблюдения. Если статус неактивен, будет запущен процесс наблюдения. Если я закрою окно приложения, запустится сторожевой процесс, и приложение снова перезапустится, и это нормально. Проблема в том, что если я закрываю приложение с помощью alt+f4 или с помощью диспетчера задач, оно перезапускает процесс, что тоже нормально, но когда я ввожу адрес электронной почты и статус утилиты пользователя активен, приложение следует закрыть, а не перезапускать снова через сторожевой процесс. Как этого добиться, пожалуйста, помогите мне.

Код: Выделить всё

import keyboard
import tkinter as tk
from tkinter import messagebox
import requests
import re
import os
import sys
import time
import subprocess

# Global variable to control watchdog process and app closing
watchdog_active = False
process = None
app_closing = False

def block_keys():
# Blocking Win+D
keyboard.add_hotkey('win+d', lambda: None, suppress=True)
# Blocking Alt+Tab
keyboard.add_hotkey('alt+tab', lambda: None, suppress=True)
# Blocking Win+Tab
keyboard.add_hotkey('win+tab', lambda: None, suppress=True)
# Blocking Task Manager (Ctrl+Shift+Esc)
keyboard.add_hotkey('ctrl+shift+esc', lambda: None, suppress=True)

def unblock_keys():
# List of hotkeys to unblock
hotkeys = ['win+d', 'alt+tab', 'win+tab', 'ctrl+shift+esc']

# Unblock each hotkey if it's currently registered
for hotkey in hotkeys:
if hotkey in keyboard._hotkeys:
keyboard.remove_hotkey(hotkey)
else:
# print(f"Hotkey {hotkey} is not registered.")
return True

# Watchdog process function (simulation)
def start_watchdog():
global watchdog_active, process
watchdog_active = True
print("Watchdog process started")

app_name = "test2.py"  # Replace with your actual app filename

while watchdog_active:
# Check if the app is running
if process is None or process.poll() is not None and watchdog_active:
# App is not running or closed, restart the app
print("App closed.  Restarting the application...")
process = subprocess.Popen([sys.executable, app_name])

time.sleep(5)  # Check every 5 seconds

def terminate_watchdog():
global watchdog_active, process
print("Watchdog process terminated")
watchdog_active = False  # Stop the loop in start_watchdog()

# If the process is running, terminate it
if process is not None:
process.terminate()
process = None

# Function to close the application
def close_app():
global app_closing
print("Closing the application")
app_closing = True  # Indicate that the app is being intentionally closed
terminate_watchdog()  # Terminate the watchdog process before closing
sys.exit()

# Function to validate email format
def is_valid_email(email):
# Regex pattern for a basic email validation
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(pattern, email) is not None

# Simulating an API call to check password validity
def check_password_with_api(password):
api_url = "http://localhost/utilitysoftwareapp/api/check-default-password"
# api_url = "https://utilitysoftwareapp.levenex.in/api/check-default-password"
response = requests.post(api_url, data={'password': password})
response_data = response.json()

return response_data['status']

# Simulate an API call to check if a user exists based on the email
def check_user_exists_with_api(email):
# Validate email format before proceeding
if not is_valid_email(email):
print("Invalid email address!")
return False, None

# Proceed with API call if email is valid
api_url = "http://localhost/utilitysoftwareapp/api/check-user-exists"
# api_url = "https://utilitysoftwareapp.levenex.in/api/check-user-exists"
response = requests.post(api_url, data={'email': email})
response_data = response.json()

return response_data['exists'], response_data['utility_status']

# Simulate an API call to register a new user
def register_user_with_api(name, email):
api_url = "http://localhost/utilitysoftwareapp/api/save-user-info"
# api_url = "https://utilitysoftwareapp.levenex.in/api/save-user-info"
response = requests.post(api_url, data={'name': name, 'email': email})
response_data = response.json()

return response_data['status']

# Function to handle password submission
def check_password():
entered_password = password_entry.get()
if check_password_with_api(entered_password):
show_email_screen()
else:
messagebox.showerror("Error", "Incorrect password, try again.")

# Function to check if a user exists
def check_user():
email = email_entry.get()

# Validate email format
if not is_valid_email(email):
# Display a message box with an error if email is invalid
messagebox.showerror("Invalid Email", "Please enter a valid email address.")
return

exists, utility_status = check_user_exists_with_api(email)

if exists:
if utility_status == "active":
messagebox.showinfo("Info", "You have an active utility. Closing the application.")
unblock_keys()
root.quit()
else:
messagebox.showinfo("Info", "No active utility. Locking the screen.")
lock_screen()
else:
show_registration_screen()

# Function to handle registration
def register_user():
name = name_entry.get()
email = email_entry.get()

if register_user_with_api(name, email):
messagebox.showinfo("Success", "Registration successful!")
show_email_screen()
else:
messagebox.showerror("Error", "Registration failed.  Please try again.")

# Function to lock the screen if no active utility
def lock_screen():
# Check if the lock label already exists
if not hasattr(root, 'lock_label'):
root.lock_label = tk.Label(root, text="System is locked.", font=("Arial", 20))
root.lock_label.pack(pady=20)
block_keys()

# Function to show the email entry screen
def show_email_screen():
clear_screen()

email_label = tk.Label(root, text="Enter your email address:", font=("Arial", 20))
email_label.pack(pady=20)

global email_entry
email_entry = tk.Entry(root, font=("Arial", 20))
email_entry.pack(pady=20)

check_button = tk.Button(root, text="Check", command=check_user, font=("Arial", 20))
check_button.pack(pady=20)

# Function to show the registration screen if user doesn't exist
def show_registration_screen():
clear_screen()

name_label = tk.Label(root, text="Enter your name:", font=("Arial", 20))
name_label.pack(pady=20)

global name_entry
name_entry = tk.Entry(root, font=("Arial", 20))
name_entry.pack(pady=20)

email_label = tk.Label(root, text="Enter your email address:", font=("Arial", 20))
email_label.pack(pady=20)

global email_entry
email_entry = tk.Entry(root, font=("Arial", 20))
email_entry.pack(pady=20)

register_button = tk.Button(root, text="Register", command=register_user, font=("Arial", 20))
register_button.pack(pady=20)

# Utility function to clear the screen
def clear_screen():
for widget in root.winfo_children():
widget.destroy()

# Create the main application window
root = tk.Tk()
root.attributes("-fullscreen", True)  # Make the window fullscreen
root.title("Levenex utility App")

# Create a label and entry for the password
password_label = tk.Label(root, text="Enter your password:", font=("Arial", 20))
password_label.pack(pady=20)

password_entry = tk.Entry(root, show="*", font=("Arial", 20))
password_entry.pack(pady=20)

# Create a button to check the password
submit_button = tk.Button(root, text="Submit", command=check_password, font=("Arial", 20))
submit_button.pack(pady=20)

# Block the win+d, win+tab, alt+tab, ctrl+shif+esc
block_keys()

# Start the Tkinter event loop
root.mainloop()

# Block the win+d, win+tab, alt+tab, ctrl+shif+esc
# Block the win+d, win+tab, alt+tab, ctrl+shif+esc
unblock_keys()

# Adding watchdog integration

import threading
import time

# Function to check the utility status
def get_utility_status():
global app_closing
try:
email = email_entry.get()
api_url = "http://localhost/utilitysoftwareapp/api/check-utility-status"
response = requests.post(api_url, data={'email': email})
response_data = response.json()
app_closing = True  # Mark utility status as checked
return response_data['utility_status']  # Assumed to be 'active' or 'inactive'
except Exception as e:
print(f"Error fetching utility status: {e}")
return 'inactive'

def main():
global app_closing

# Don't check utility status if the app is being closed
if not app_closing:
# Check utility status every time
utility_status = get_utility_status()

if utility_status == 'active':
print("utility is active. Terminating watchdog process and closing the app...")
terminate_watchdog()  # Terminate watchdog when utility status is active
close_app()  # Close the application
else:
print("utility is inactive or an error occurred. Watchdog remains active...")
start_watchdog()
else:
print("App is closing, skipping utility status check.")

if __name__ == "__main__":
main()`
Я добился одного из тех пунктов, которые хотел. Приложение закрывается в первый раз, когда статус утилиты активен. Проблема возникает после закрытия приложения с помощью alt+f4 или диспетчера задач, а затем после перезапуска приложения через процесс наблюдения оно должно закрыться, если статус утилиты активен. Окно закроется, но перезапустится снова.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ython-tkin

Вернуться в «Python»