create a simple gui app with pyside6 to ping an address with start and stop button, last used ping will be saved and loaded automatically in json
Assistant
Certainly! Below is a complete Python script that uses PySide6 to create a simple GUI application for pinging an address. The application includes Start and Stop buttons to control the ping process and automatically saves the last used address in a JSON file (config.json). Upon restarting the application, it will load the last used address automatically.
Prerequisites
Python 3.6 or higher: Ensure you have Python installed. You can download it from python.org.
PySide6: Install the PySide6 library using pip:
bash
pip install PySide6
Complete Code
python
import sys
import json
import subprocess
import platform
from PySide6.QtCore import QThread, Signal, Qt
from PySide6.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLineEdit,
QPushButton,
QTextEdit,
QLabel,
QMessageBox,
)
CONFIG_FILE = "config.json"
class PingThread(QThread):
output_received = Signal(str)
finished = Signal()
def __init__(self, address):
super().__init__()
self.address = address
self._is_running = True
def run(self):
# Determine the parameter based on the OS
param = "-n" if platform.system().lower() == "windows" else "-c"
# Start the ping process
process = subprocess.Popen(
["ping", param, "4", self.address],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
while self._is_running:
line = process.stdout.readline()
if not line:
break
self.output_received.emit(line)
# Terminate the process if it's still running
if process.poll() is None:
process.terminate()
self.finished.emit()
def stop(self):
self._is_running = False
self.wait()
class PingApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Ping Application")
self.setGeometry(100, 100, 600, 400)
self.ping_thread = None
self.init_ui()
self.load_config()
def init_ui(self):
layout = QVBoxLayout()
# Address input layout
address_layout = QHBoxLayout()
self.address_label = QLabel("Address:")
self.address_input = QLineEdit()
address_layout.addWidget(self.address_label)
address_layout.addWidget(self.address_input)
layout.addLayout(address_layout)
# Buttons layout
buttons_layout = QHBoxLayout()
self.start_button = QPushButton("Start")
self.stop_button = QPushButton("Stop")
self.stop_button.setEnabled(False) # Initially disabled
self.start_button.clicked.connect(self.start_ping)
self.stop_button.clicked.connect(self.stop_ping)
buttons_layout.addWidget(self.start_button)
buttons_layout.addWidget(self.stop_button)
layout.addLayout(buttons_layout)
# Output display
self.output_display = QTextEdit()
self.output_display.setReadOnly(True)
layout.addWidget(self.output_display)
self.setLayout(layout)
def start_ping(self):
address = self.address_input.text().strip()
if not address:
QMessageBox.warning(self, "Input Error", "Please enter an address to ping.")
return
# Disable start button and enable stop button
self.start_button.setEnabled(False)
self.stop_button.setEnabled(True)
# Clear previous output
self.output_display.clear()
# Start the ping thread
self.ping_thread = PingThread(address)
self.ping_thread.output_received.connect(self.update_output)
self.ping_thread.finished.connect(self.ping_finished)
self.ping_thread.start()
def stop_ping(self):
if self.ping_thread and self.ping_thread.isRunning():
self.ping_thread.stop()
self.output_display.append("\nPing stopped by user.")
# Disable stop button and enable start button
self.stop_button.setEnabled(False)
self.start_button.setEnabled(True)
def ping_finished(self):
# Enable start button and disable stop button
self.start_button.setEnabled(True)
self.stop_button.setEnabled(False)
def update_output(self, text):
self.output_display.append(text)
def load_config(self):
try:
with open(CONFIG_FILE, "r") as f:
config = json.load(f)
last_address = config.get("last_address", "")
self.address_input.setText(last_address)
except FileNotFoundError:
# Config file does not exist; do nothing
pass
except json.JSONDecodeError:
QMessageBox.warning(self, "Config Error", "Failed to parse config.json.")
def save_config(self):
config = {
"last_address": self.address_input.text().strip()
}
try:
with open(CONFIG_FILE, "w") as f:
json.dump(config, f)
except Exception as e:
QMessageBox.warning(self, "Save Error", f"Failed to save config: {e}")
def closeEvent(self, event):
# Save config on close
self.save_config()
# Stop the ping thread if it's running
if self.ping_thread and self.ping_thread.isRunning():
self.ping_thread.stop()
event.accept()
def main():
app = QApplication(sys.argv)
window = PingApp()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
Explanation of the Code
Imports and Configuration:
Standard Libraries:
sys, json, subprocess, platform: For system operations, JSON handling, executing ping commands, and determining the operating system.
PySide6 Modules:
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton, QTextEdit, QLabel, QMessageBox: For creating the GUI components.
QThread, Signal: For handling the ping process in a separate thread to keep the GUI responsive.
PingThread Class:
Inherits from QThread to run the ping command without freezing the GUI.
Signals:
output_received: Emitted when a new line of ping output is received.
finished: Emitted when the ping process finishes.
Methods:
run(): Executes the ping command using subprocess.Popen and reads the output line by line, emitting each line through the output_received signal. It keeps running until _is_running is set to False.
stop(): Sets _is_running to False and waits for the thread to finish.
PingApp Class:
Inherits from QWidget and sets up the main window.
Initialization:
Sets window title and size.
Initializes the UI components and loads the last used address from config.json.
UI Components:
Address Input:
QLabel and QLineEdit for entering the address to ping.
Buttons:
Running the Application
Save the Script:
Save the provided Python script to a file, e.g., ping_app.py.
Install Dependencies:
Ensure you have PySide6 installed. If not, install it using pip:
bash
pip install PySide6
Run the Application:
Execute the script using Python:
bash
python ping_app.py
Using the Application:
Enter Address: Input the IP address or hostname you wish to ping in the address field.
Start Pinging: Click the Start button to begin pinging. The ping results will appear in the text area.
Stop Pinging: Click the Stop button to terminate the ping process.
Automatic Saving: The last entered address is automatically saved in config.json and loaded the next time you run the application.
Notes
Cross-Platform Compatibility: The script determines the appropriate ping command parameters based on the operating system (Windows or Unix-like systems).
Thread Safety:PingThread runs in a separate thread to ensure the GUI remains responsive during the ping process.
Error Handling: The application includes basic error handling for missing input and issues with the configuration file.
Feel free to customize and enhance the application further based on your requirements!
Not yet included in a published release.
Start button to begin pinging.
Stop button to terminate pinging. Initially disabled.
Output Display:
QTextEdit to display the ping results. Set to read-only.
Functionality:
start_ping(): Validates the input, disables the Start button, enables the Stop button, clears previous output, and starts the PingThread.
stop_ping(): Stops the ping thread, appends a message indicating the ping was stopped, disables the Stop button, and re-enables the Start button.
update_output(text): Appends each line of ping output to the QTextEdit.
ping_finished(): Called when the ping thread finishes; re-enables and disables the appropriate buttons.
load_config(): Loads the last used address from config.json if it exists.
save_config(): Saves the current address to config.json.
closeEvent(event): Overrides the close event to ensure configuration is saved and the ping thread is properly terminated.
Main Function:
Initializes the QApplication, creates an instance of PingApp, displays the window, and starts the event loop.