def main(): Initialize PyQt5 application app = QApplication(sys.argv) lockmanager =…
- User
def main(): # Initialize PyQt5 application app = QApplication(sys.argv)
code - Assistant
def main(): # Initialize PyQt5 application app = QApplication(sys.argv)
lock_manager = LockManager(LOCK_FILE)
try:
lock_manager.acquire()
except (IOError, OSError):
QMessageBox.warning(None, "", "The program is already running.")
if lock_manager.file:
lock_manager.file.close()
sys.exit()
atexit.register(lock_manager.release)
# Your main program logic here
print("Program is running...")
global MAX_PINGS, MAX_WORKERS
tab_widget = QTabWidget()
# Initialize SoundManager (assuming this is defined elsewhere in your code)
sound_manager = SoundManager()
# Main widget and layout setup
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# UI setup (e.g., labels for status information)
host_label = QLabel()
host_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
host_label.setStyleSheet("font-size: 12pt; color: black; padding-right: 10px;")
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
# Arrange layout
main_layout.addWidget(host_label)
main_layout.addWidget(tab_widget)
main_layout.addWidget(clock_label)
main_widget.setLayout(main_layout)
main_widget.setWindowTitle("Server Monitor - Alert by IT Servicedesk 2014")
main_widget.setGeometry(300, 300, 1100, 600)
# Function to update status labels
def update_labels():
current_time = QTime.currentTime().toString("hh:mm:ss")
current_date = QDate.currentDate().toString("dd MMM yyyy")
# Assuming host_info_dict is defined/available
total_hosts = len(host_info_dict)
offline_hosts = 0 # Implement logic to determine online/offline hosts
offline_hosts_wan = 0 # Implement logic to specifically track WAN status
offline_hosts_serv = 0 # Implement logic for Server status
for row in range(main_window.table_widget.rowCount()):
item = main_window.table_widget.item(row, 0) # Assuming the hostname is in the first column
if item is not None:
inspect_status = main_window.table_widget.item(row, 6).text() # Assuming the inspect status is in the 7th column
if inspect_status != 'Server up':
offline_hosts += 1
if inspect_status == 'WAN down':
offline_hosts_wan += 1
elif inspect_status == 'Server down':
offline_hosts_serv += 1
online_hosts = total_hosts - (offline_hosts_wan + offline_hosts_serv)
# Example label updates
host_label.setText(f"Total: {total_hosts} Online: {total_hosts - offline_hosts} Offline: {offline_hosts} [ Server: {offline_hosts_serv} Wan: {offline_hosts_wan} ]")
clock_label.setText(f"{current_date} - {current_time} ")
# Timer for updating labels
timer = QTimer()
timer.timeout.connect(update_labels)
timer.start(1000) # Update every second
# Create main UI components
main_window = OfflineHostMonitor(None, None, None, None)
tab_widget.addTab(main_window, "Monitor")
return_online_widget = ReturnOnlineWidget()
tab_widget.addTab(return_online_widget, "Return Online")
main_window.sound_manager = sound_manager # Attach the sound manager to the main window
settings_widget = SettingsWidget(None, None, None, None, None, tab_widget, main_window)
tab_widget.addTab(settings_widget, "Settings")
update_log_widget = UpdateLogWidget()
tab_widget.addTab(update_log_widget, "Update Log")
main_window.settings_widget = settings_widget
# Prepare application exit cleanup
def cleanup():
# Display the closing dialog
closing_dialog = ClosingDialog()
closing_dialog.show()
app.processEvents() # Process remaining GUI events
stop_event.set() # Signal all threads to stop
for thread in active_threads:
thread.join() # Wait for threads to finish
# Close the dialog after threads are done
closing_dialog.accept()
# Connect cleanup on application exit
app.aboutToQuit.connect(cleanup)
# File path setup and initial checks
file_path = 'hostname.txt'
offline_state_file = 'offline_state.json'
if not os.path.exists(file_path):
QMessageBox.critical(None, "File Not Found", "The file 'hostname.txt' was not found. Exiting the application.")
sys.exit()
host_info_list, hostname_count = read_host_list(file_path)
print(f"Number of hostnames in file: {hostname_count}")
if not host_info_list:
sys.exit()
# Load offline state
offline_dict = load_offline_state(offline_state_file)
host_info_dict = {hostname.upper(): (hostname, store_name, telephone, wan_a, wan_b) for hostname, store_name, telephone, wan_a, wan_b in host_info_list}
offline_dict = {hostname: details for hostname, details in offline_dict.items() if hostname in host_info_dict}
# Queue and threading setup
queue = Queue()
stop_event = threading.Event()
active_threads = []
cpu_count = psutil.cpu_count(logical=True)
memory = psutil.virtual_memory()
available_memory_gb = memory.available / (1024 ** 2)
max_pings_based_on_memory = int(available_memory_gb / 0.1)
MAX_PINGS = min(MAX_PINGS, max_pings_based_on_memory)
semaphore = threading.Semaphore(MAX_PINGS)
# Assign globals to widgets
main_window.queue = queue
main_window.offline_dict = offline_dict
main_window.stop_event = stop_event
main_window.semaphore = semaphore
settings_widget.queue = queue
settings_widget.offline_dict = offline_dict
settings_widget.stop_event = stop_event
settings_widget.semaphore = semaphore
settings_widget.host_info_list = host_info_list
return_online_signal = return_online_widget.dataUpdated
# Start monitoring threads for each host
for host_info in host_info_list:
thread = threading.Thread(
target=monitor_host,
args=(host_info, queue, offline_dict, stop_event, semaphore, main_window)
)
thread.start()
active_threads.append(thread)
# Start thread to handle offline list updates
update_thread = threading.Thread(
target=update_offline_list,
args=(queue, offline_dict, stop_event, return_online_signal, settings_widget, main_window),
daemon=True
)
update_thread.start()
active_threads.append(update_thread)
# Show main widget
main_widget.show()
# Ensure state is saved on app quit
app.aboutToQuit.connect(lambda: save_offline_state(offline_state_file, offline_dict))
sys.exit(app.exec_())
make line that show date and time, divide it to 2 by second show date time and first part show all text from print command
To achieve your goal of displaying both the date and time, and the output from print statements on your GUI application, you can redirect the standard output (sys.stdout) to a custom class that emits a signal every time text is written. This signal can then be connected to a function that updates a label in your GUI.
Here's how you can modify your code to implement this functionality:
Create a custom class to redirect sys.stdout: This class will inherit from QObject and will have a signal that emits any text written to it.
Add two labels to display the date/time and the print outputs: Use a horizontal layout to arrange these labels in a single line.
Update the labels accordingly: Use a timer to update the date/time label every second and connect the print output label to the custom sys.stdout.
Below is the modified code incorporating these changes:
import sys
import threading
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox, QTabWidget
from PyQt5.QtCore import QObject, pyqtSignal, QTimer, QTime, QDate, Qt
import psutil
# Your other imports (e.g., SoundManager, LockManager, etc.)
class EmittingStream(QObject):
textWritten = pyqtSignal(str)
def write(self, text):
if text.strip() != '':
self.textWritten.emit(str(text))
def flush(self):
pass # Needed for compatibility with sys.stdout
def main():
# Initialize PyQt5 application
app = QApplication(sys.argv)
# ... (Your existing code for LockManager and initialization)
# Initialize SoundManager (assuming this is defined elsewhere in your code)
sound_manager = SoundManager()
# Main widget and layout setup
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# UI setup: labels for status information
# Create a horizontal layout to hold both labels
label_layout = QHBoxLayout()
# Label to display print outputs
print_label = QLabel()
print_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
print_label.setStyleSheet("font-size: 12pt; color: black; padding-left: 10px;")
# Label to display date and time
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
# Add labels to the horizontal layout
label_layout.addWidget(print_label)
label_layout.addStretch() # This pushes the clock_label to the right
label_layout.addWidget(clock_label)
# Add the label layout to the main layout
main_layout.addLayout(label_layout)
# Rest of your main layout setup (e.g., adding tab_widget)
tab_widget = QTabWidget()
main_layout.addWidget(tab_widget)
main_widget.setLayout(main_layout)
main_widget.setWindowTitle("Server Monitor - Alert by IT Servicedesk 2014")
main_widget.setGeometry(300, 300, 1100, 600)
# Function to update the clock label
def update_clock():
current_time = QTime.currentTime().toString("hh:mm:ss")
current_date = QDate.currentDate().toString("dd MMM yyyy")
clock_label.setText(f"{current_date} - {current_time} ")
# Timer for updating the clock label every second
timer = QTimer()
timer.timeout.connect(update_clock)
timer.start(1000) # Update every second
# Redirect sys.stdout to the print_label
sys.stdout = EmittingStream()
sys.stdout.textWritten.connect(lambda text: print_label.setText(text))
# Your existing code to create main_window, tabs, and initialize threads
# Create main UI components
main_window = OfflineHostMonitor(None, None, None, None)
tab_widget.addTab(main_window, "Monitor")
return_online_widget = ReturnOnlineWidget()
tab_widget.addTab(return_online_widget, "Return Online")
main_window.sound_manager = sound_manager # Attach the sound manager to the main window
settings_widget = SettingsWidget(None, None, None, None, None, tab_widget, main_window)
tab_widget.addTab(settings_widget, "Settings")
update_log_widget = UpdateLogWidget()
tab_widget.addTab(update_log_widget, "Update Log")
main_window.settings_widget = settings_widget
# ... (Your existing code for cleanup and threading)
# Show main widget
main_widget.show()
# Ensure state is saved on app quit
app.aboutToQuit.connect(lambda: save_offline_state(offline_state_file, offline_dict))
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Explanation of the Changes:
EmittingStream Class: This class acts as a custom stream that emits any text written to it through the textWritten signal. By connecting this signal to the setText method of print_label, any text sent to sys.stdout (using print) will be displayed in print_label.
class EmittingStream(QObject):
textWritten = pyqtSignal(str)
def write(self, text):
if text.strip() != '':
self.textWritten.emit(str(text))
def flush(self):
pass
Redirecting sys.stdout: After creating the EmittingStream instance, we redirect sys.stdout to it. This means any print statements will now emit signals that we can use within the GUI.
sys.stdout = EmittingStream()
sys.stdout.textWritten.connect(lambda text: print_label.setText(text))
Labels and Layout: We added two labels (print_label and clock_label) to display the print outputs and the date/time, respectively. These labels are added to a horizontal layout (label_layout), which is then added to the main layout.
# Label to display print outputs
print_label = QLabel()
print_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
print_label.setStyleSheet("font-size: 12pt; color: black; padding-left: 10px;")
# Label to display date and time
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
# Add labels to the horizontal layout
label_layout.addWidget(print_label)
label_layout.addStretch() # This pushes the clock_label to the right
label_layout.addWidget(clock_label)
# Add the label layout to the main layout
main_layout.addLayout(label_layout)
Notes:
The EmittingStream class captures text written to sys.stdout and emits it via the textWritten signal.
The print_label only displays the latest text from the print statements. If you want to accumulate all printed text, you can modify the on_update_text function to append the text instead of replacing it.
For example:
def on_update_text(self, text):
existing_text = self.print_label.text()
updated_text = existing_text + text
self.print_label.setText(updated_text)
However, be cautious with accumulating text in a label, as it can grow indefinitely and may affect performance. Consider adding a maximum length or clear it periodically.
With these changes, your application will now display all text from print statements on the left side of the line and the current date and time on the right, updating every second.
Not yet included in a published release.
Updating the Clock Label: A separate function update_clock is used to update the clock_label every second using a QTimer.
def update_clock():
current_time = QTime.currentTime().toString("hh:mm:ss")
current_date = QDate.currentDate().toString("dd MMM yyyy")
clock_label.setText(f"{current_date} - {current_time} ")
# Timer for updating the clock label every second
timer = QTimer()
timer.timeout.connect(update_clock)
timer.start(1000) # Update every second
Cleanup on Exit: It's good practice to reset sys.stdout to its original state when the application exits.
def closeEvent(self, event):
sys.stdout = sys.__stdout__ # Reset stdout
event.accept()