Certainly! Below is a simple PySide6 application that allows users to:
- Select or enter an IP address from a dropdown (with previously used IPs saved in a JSON file).
- Specify the number of ping attempts.
- Start and stop the ping process.
- Display the ping results in a text area.
Prerequisites
Make sure you have PySide6 installed. You can install it using pip:
pip install PySide6
Complete Code Example
import sys
import json
import os
import subprocess
import platform
from PySide6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLineEdit, QLabel, QComboBox, QTextEdit, QMessageBox
)
from PySide6.QtCore import QThread, Signal
# Constants
JSON_FILE = "last_used_ips.json"
class PingThread(QThread):
output_signal = Signal(str)
finished_signal = Signal()
def __init__(self, ip, count):
super().__init__()
self.ip = ip
self.count = count
self._is_running = True
def run(self):
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, str(self.count), self.ip]
try:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
for line in process.stdout:
if not self._is_running:
process.terminate()
break
self.output_signal.emit(line)
process.wait()
except Exception as e:
self.output_signal.emit(f"Error: {str(e)}\n")
self.finished_signal.emit()
def stop(self):
self._is_running = False
class PingApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Ping Application")
self.resize(600, 400)
self.ping_thread = None
self.init_ui()
self.load_ips()
def init_ui(self):
layout = QVBoxLayout()
# IP Input Layout
ip_layout = QHBoxLayout()
ip_label = QLabel("IP Address:")
self.ip_combo = QComboBox()
self.ip_combo.setEditable(True)
ip_layout.addWidget(ip_label)
ip_layout.addWidget(self.ip_combo)
layout.addLayout(ip_layout)
# Ping Count Layout
count_layout = QHBoxLayout()
count_label = QLabel("Ping Count:")
self.count_input = QLineEdit()
self.count_input.setPlaceholderText("Enter number of pings")
self.count_input.setFixedWidth(100)
count_layout.addWidget(count_label)
count_layout.addWidget(self.count_input)
count_layout.addStretch()
layout.addLayout(count_layout)
# Buttons Layout
buttons_layout = QHBoxLayout()
self.start_btn = QPushButton("Start")
self.stop_btn = QPushButton("Stop")
self.stop_btn.setEnabled(False)
buttons_layout.addWidget(self.start_btn)
buttons_layout.addWidget(self.stop_btn)
buttons_layout.addStretch()
layout.addLayout(buttons_layout)
# Output Text Area
self.output_area = QTextEdit()
self.output_area.setReadOnly(True)
layout.addWidget(self.output_area)
self.setLayout(layout)
# Connect signals
self.start_btn.clicked.connect(self.start_pinging)
self.stop_btn.clicked.connect(self.stop_pinging)
def load_ips(self):
if os.path.exists(JSON_FILE):
try:
with open(JSON_FILE, 'r') as f:
ips = json.load(f)
self.ip_combo.addItems(ips)
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to load IPs: {str(e)}")
def save_ips(self, ip):
ips = [self.ip_combo.itemText(i) for i in range(self.ip_combo.count())]
if ip and ip not in ips:
self.ip_combo.addItem(ip)
ips.append(ip)
try:
with open(JSON_FILE, 'w') as f:
json.dump(ips, f)
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to save IPs: {str(e)}")
def start_pinging(self):
ip = self.ip_combo.currentText().strip()
count_text = self.count_input.text().strip()
if not ip:
QMessageBox.warning(self, "Input Error", "Please enter a valid IP address.")
return
if not count_text.isdigit() or int(count_text) <= 0:
QMessageBox.warning(self, "Input Error", "Please enter a valid ping count.")
return
count = int(count_text)
self.ping_thread = PingThread(ip, count)
self.ping_thread.output_signal.connect(self.update_output)
self.ping_thread.finished_signal.connect(self.ping_finished)
self.ping_thread.start()
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.output_area.clear()
self.save_ips(ip)
def stop_pinging(self):
if self.ping_thread and self.ping_thread.isRunning():
self.ping_thread.stop()
self.ping_thread.wait()
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
def ping_finished(self):
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
def update_output(self, text):
self.output_area.append(text)
def closeEvent(self, event):
self.stop_pinging()
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = PingApp()
window.show()
sys.exit(app.exec())
Explanation
-
Importing Modules:
- Standard modules like
sys, json, os, subprocess, and platform are used.
PySide6 modules are used for creating the GUI and handling threads.
-
Constants:
JSON_FILE is the filename where the last used IPs are stored.
-
PingThread Class:
- Inherits from
QThread to run the ping process without freezing the GUI.
- Emits
output_signal with each line of ping output.
- Emits
finished_signal when the ping process is done or stopped.
- The
stop method allows gracefully terminating the ping process.
-
PingApp Class:
- Inherits from
QWidget and sets up the main UI.
- UI Components:
- IP Input: A
QComboBox that is editable, allowing selection from previous entries or new input.
- Ping Count Input: A
QLineEdit for specifying the number of ping attempts.
- Start and Stop Buttons: To control the ping process.
- Output Area: A
QTextEdit to display ping results.
- Methods:
load_ips: Loads IPs from the JSON file into the dropdown.
save_ips: Saves a new IP to the JSON file if it's not already present.
start_pinging: Validates inputs, starts the PingThread, and updates the UI accordingly.
stop_pinging: Stops the running PingThread and updates the UI.
ping_finished: Callback when pinging is complete to reset button states.
update_output: Appends ping output to the text area.
closeEvent: Ensures that the ping thread is stopped when the application is closed.
-
Main Execution:
- Creates the application, initializes the main window, and starts the event loop.
Running the Application
-
Save the Code:
Save the above code to a file, e.g., ping_app.py.
-
Run the Application:
python ping_app.py
-
Using the Application:
- IP Address: Select from the dropdown or enter a new IP.
- Ping Count: Enter the number of ping attempts.
- Start: Begin the ping process.
- Stop: Terminate the ping process prematurely.
- Output: View the real-time ping results.
- The IP addresses you use will be saved and loaded automatically for future use.
Notes
- Cross-Platform Support: The code adjusts the ping command parameters based on the operating system (
-n for Windows and -c for Unix/Linux).
- Error Handling: Basic error handling is included for JSON operations and subprocess execution.
- Thread Safety:
PingThread uses signals to communicate with the main thread, ensuring thread safety.
Feel free to enhance the application further by adding features like logging to a file, validating IP addresses more thoroughly, or customizing the UI.