def __init__(self):
super().__init__()
self.file_path = None
self.executor = None
def run(self):
if not self.file_path:
self.log_signal.emit("No file selected!")
return
self.log_signal.emit("Processing file...")
output_file = self.file_path.rsplit('.', 1)[0] + '_ips.csv'
futures = []
code_number_to_future = {}
results = []
total_lines = 0
# Create a new ThreadPoolExecutor instance for each run
self.executor = ThreadPoolExecutor(max_workers=10)
try:
with open(self.file_path, 'r') as infile:
lines = infile.readlines()
total_lines = len(lines)
self.progress.emit(0)
# Step 1: Resolve base IP addresses
for line in lines:
code_number = line.strip()
if code_number.isdigit():
base_hostname = f'pth{code_number}'
future = self.executor.submit(self.get_ip_from_hostname, base_hostname)
futures.append(future)
code_number_to_future[future] = code_number
else:
self.log_signal.emit(f'Invalid code number: {code_number}')
results.extend([(code_number, f'N/A.{octet}') for octet in [60, 61, 62]])
completed_futures = 0
unique_ips = set() # To track unique IP addresses
for future in as_completed(futures):
code_number = code_number_to_future[future]
base_ip = future.result()
if base_ip:
# Generate IP addresses with last octet 60, 61, and 62
for last_octet in [60, 61, 62]:
ip_address = f'{base_ip.rsplit(".", 1)[0]}.{last_octet}'
if ip_address not in unique_ips:
results.append((code_number, ip_address))
unique_ips.add(ip_address)
else:
# Handle case where base IP is not resolved
for last_octet in [60, 61, 62]:
ip_address = f'N/A.{last_octet}'
if (code_number, ip_address) not in results:
results.append((code_number, ip_address))
self.log_signal.emit(f'Processed {code_number}: {base_ip if base_ip else "N/A"}')
completed_futures += 1
self.progress.emit(int((completed_futures / len(futures)) * 100)) # Update progress as a percentage
# Final progress update to ensure it reaches 100%
self.progress.emit(100)
# Sort results by code_number
results.sort(key=lambda x: x[0])
with open(output_file, 'w') as outfile:
for code_number, ip_address in results:
outfile.write(f'{code_number},{ip_address}\n')
self.log_signal.emit(f"Processing completed. Results saved to: {output_file}")
except Exception as e:
self.log_signal.emit(f"Error occurred: {str(e)}")
finally:
if self.executor:
self.executor.shutdown(wait=True)
self.finished.emit()
def get_ip_from_hostname(self, hostname):
"""Get the IP address for a given hostname."""
try:
return socket.gethostbyname(hostname)
except socket.gaierror:
return None
class IPResolver(QMainWindow):
def init(self):
super().init()
self.initUI()
if name == 'main':
app = QApplication(sys.argv)
window = IPResolver()
window.show()
sys.exit(app.exec_())
change option load file or can pasting text box for load data and make retrive button
Sure! To enhance your PyQt5 application by allowing users to either load a file or paste data directly into a text box, and to add a "Retrieve" button for processing, you can follow the updated code and explanations below.
Key Changes:
UI Enhancements:
Text Box for Pasting Data: Added a QTextEdit widget where users can paste code numbers directly.
Retrieve Button: Added a Retrieve button that initiates the processing of either the loaded file or the pasted data.
Worker Class Modifications:
Handling Pasted Data: Updated the Worker class to accept either a file path or a list of code numbers.
Processing Logic: Adjusted the run method to process based on the available input (file or pasted data).
Main Window Adjustments:
Input Source Management: Managed the precedence of input sources (file vs. pasted data).
UI Layout: Organized the widgets for better user experience.
Updated Code:
python
import sys
import socket
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QFileDialog, QPushButton,
QTextEdit, QVBoxLayout, QWidget, QProgressBar, QLabel, QHBoxLayout
)
from PyQt5.QtCore import QThread, pyqtSignal, QObject
from concurrent.futures import ThreadPoolExecutor, as_completed
class Worker(QObject):
progress = pyqtSignal(int)
finished = pyqtSignal()
log_signal = pyqtSignal(str)
def __init__(self):
super().__init__()
self.file_path = None
self.pasted_data = None
self.executor = None
def run(self):
data_source = []
if self.file_path:
try:
with open(self.file_path, 'r') as infile:
data_source = infile.readlines()
self.log_signal.emit(f"Loaded {len(data_source)} lines from file.")
except Exception as e:
self.log_signal.emit(f"Error loading file: {str(e)}")
self.finished.emit()
return
elif self.pasted_data:
data_source = self.pasted_data.strip().splitlines()
self.log_signal.emit(f"Loaded {len(data_source)} lines from pasted data.")
else:
self.log_signal.emit("No input data provided!")
self.finished.emit()
return
if not data_source:
self.log_signal.emit("Input data is empty!")
self.finished.emit()
return
self.log_signal.emit("Processing data...")
output_file = ""
if self.file_path:
output_file = self.file_path.rsplit('.', 1)[0] + '_ips.csv'
else:
output_file = 'pasted_data_ips.csv'
futures = []
code_number_to_future = {}
results = []
total_lines = len(data_source)
# Create a new ThreadPoolExecutor instance for each run
self.executor = ThreadPoolExecutor(max_workers=10)
try:
# Step 1: Resolve base IP addresses
for line in data_source:
code_number = line.strip()
if code_number.isdigit():
base_hostname = f'pth{code_number}'
future = self.executor.submit(self.get_ip_from_hostname, base_hostname)
futures.append(future)
code_number_to_future[future] = code_number
else:
self.log_signal.emit(f'Invalid code number: {code_number}')
for octet in [60, 61, 62]:
results.append((code_number, f'N/A.{octet}'))
completed_futures = 0
unique_ips = set() # To track unique IP addresses
for future in as_completed(futures):
code_number = code_number_to_future[future]
base_ip = future.result()
if base_ip:
# Generate IP addresses with last octet 60, 61, and 62
for last_octet in [60, 61, 62]:
ip_address = f'{base_ip.rsplit(".", 1)[0]}.{last_octet}'
if ip_address not in unique_ips:
results.append((code_number, ip_address))
unique_ips.add(ip_address)
else:
# Handle case where base IP is not resolved
for last_octet in [60, 61, 62]:
ip_address = f'N/A.{last_octet}'
results.append((code_number, ip_address))
self.log_signal.emit(f'Processed {code_number}: {base_ip if base_ip else "N/A"}')
completed_futures += 1
self.progress.emit(int((completed_futures / len(futures)) * 100)) # Update progress as a percentage
# Final progress update to ensure it reaches 100%
self.progress.emit(100)
# Sort results by code_number
results.sort(key=lambda x: x[0])
with open(output_file, 'w') as outfile:
for code_number, ip_address in results:
outfile.write(f'{code_number},{ip_address}\n')
self.log_signal.emit(f"Processing completed. Results saved to: {output_file}")
except Exception as e:
self.log_signal.emit(f"Error occurred: {str(e)}")
finally:
if self.executor:
self.executor.shutdown(wait=True)
self.finished.emit()
def get_ip_from_hostname(self, hostname):
"""Get the IP address for a given hostname."""
try:
return socket.gethostbyname(hostname)
except socket.gaierror:
return None
class IPResolver(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('IP Resolver')
self.setGeometry(100, 100, 700, 500)
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout()
central_widget.setLayout(main_layout)
# Section for File Loading
file_layout = QHBoxLayout()
self.btn_load = QPushButton('Load File')
self.btn_load.clicked.connect(self.load_file)
self.lbl_file = QLabel("No file selected.")
file_layout.addWidget(self.btn_load)
file_layout.addWidget(self.lbl_file)
main_layout.addLayout(file_layout)
# Divider
divider = QLabel("OR")
divider.setAlignment(Qt.AlignCenter)
main_layout.addWidget(divider)
# Section for Pasted Data
self.paste_area = QTextEdit()
self.paste_area.setPlaceholderText("Paste your code numbers here, one per line...")
main_layout.addWidget(self.paste_area)
# Retrieve Button
self.btn_retrieve = QPushButton('Retrieve')
self.btn_retrieve.clicked.connect(self.start_worker)
main_layout.addWidget(self.btn_retrieve)
# Log Area
self.log_area = QTextEdit()
self.log_area.setReadOnly(True)
main_layout.addWidget(self.log_area)
# Progress Bar
self.progress_bar = QProgressBar()
self.progress_bar.setValue(0)
main_layout.addWidget(self.progress_bar)
# Initialize Worker and Thread
self.worker_thread = QThread()
self.worker = Worker()
self.worker.moveToThread(self.worker_thread)
self.worker.progress.connect(self.update_progress)
self.worker.finished.connect(self.on_worker_finished)
self.worker.log_signal.connect(self.log)
self.worker_thread.started.connect(self.worker.run)
self.file_path = None
def load_file(self):
file_name, _ = QFileDialog.getOpenFileName(
self, "Select Input File", "", "Text Files (*.txt);;All Files (*)"
)
if file_name:
self.file_path = file_name
self.lbl_file.setText(file_name)
self.log(f"Selected file: {file_name}")
else:
self.log("File selection canceled.")
def start_worker(self):
# Determine the input source
pasted_text = self.paste_area.toPlainText().strip()
if not self.file_path and not pasted_text:
self.log("No input provided. Please load a file or paste data.")
return
# Avoid processing both file and pasted data at the same time
if self.file_path and pasted_text:
self.log("Both file and pasted data detected. Processing file only.")
data_to_use = 'file'
elif self.file_path:
data_to_use = 'file'
else:
data_to_use = 'pasted'
self.worker.file_path = self.file_path if data_to_use == 'file' else None
self.worker.pasted_data = pasted_text if data_to_use == 'pasted' else None
# Reset progress and log
self.progress_bar.setValue(0)
self.log_area.clear()
# Start the worker thread
if not self.worker_thread.isRunning():
self.worker_thread.start()
self.log("Worker thread started.")
else:
self.log("Worker thread is already running.")
def update_progress(self, value):
self.progress_bar.setValue(value)
def on_worker_finished(self):
self.log("Processing finished.")
self.worker_thread.quit()
self.worker_thread.wait()
self.log("Worker thread terminated.")
def log(self, message):
self.log_area.append(message)
def closeEvent(self, event):
# Ensure the worker thread is properly closed when the application exits
if self.worker_thread.isRunning():
self.worker_thread.quit()
self.worker_thread.wait()
event.accept()
if __name__ == '__main__':
from PyQt5.QtCore import Qt # Import Qt for alignment
app = QApplication(sys.argv)
window = IPResolver()
window.show()
sys.exit(app.exec_())
Detailed Explanation of Changes:
UI Enhancements:
File Selection Section:
Added a QLabel (self.lbl_file) to display the selected file path.
Organized the "Load File" button and label horizontally using a QHBoxLayout.
Divider Label:
Added a centered "OR" label to indicate alternative input methods.
Pasted Data Section:
Added a QTextEdit (self.paste_area) where users can paste code numbers directly.
Set a placeholder text to guide users.
Retrieve Button:
The "Retrieve" button (self.btn_retrieve) is moved below the pasted data section.
Connected to the start_worker method to initiate processing.
Worker Class Modifications:
Input Handling:
Added a self.pasted_data attribute to store pasted data.
Modified the run method to prioritize file input over pasted data. If both are provided, it processes the file and ignores the pasted data, logging a message accordingly.
If only pasted data is available, it processes the pasted lines.
Output File Naming:
If processing pasted data, results are saved to a default filename (pasted_data_ips.csv).
Main Window (IPResolver) Adjustments:
load_file Method:
Updates the self.lbl_file with the selected file's path.
Logs the selected file or cancellation.
start_worker Method:
Checks which input source is being used (file or pasted data).
Ensures that both sources are not processed simultaneously. If both are provided, it gives precedence to the file.
Sets the appropriate attributes in the Worker instance (file_path or pasted_data).
Clears previous logs and resets the progress bar before starting.
Usage Instructions:
Loading from a File:
Click the "Load File" button.
Select a .txt file containing code numbers, one per line.
The selected file path will be displayed.
Optionally, you can also paste data into the text box, but the file input takes precedence.
Click the "Retrieve" button to start processing.
Pasting Data Directly:
Paste your code numbers into the provided text box, one per line.
Ensure no file is loaded if you intend to use the pasted data.
Click the "Retrieve" button to start processing.
Viewing Logs and Progress:
The Log Area will display real-time messages about the processing status.
The Progress Bar indicates the completion percentage.
Output:
Results are saved as a .csv file in the same directory as the input file or as pasted_data_ips.csv if using pasted data.
Final Notes:
Thread Management: The worker runs in a separate thread to keep the UI responsive. Ensure that the thread is properly managed to avoid any potential issues when starting or stopping processes.
Error Handling: The application includes basic error handling. Depending on your use case, you might want to enhance it further to cover more edge cases.
Dependencies: Ensure that PyQt5 is installed in your Python environment. You can install it using:
bash
pip install PyQt5
This updated application provides flexibility for users to either load a file or paste data directly, enhancing usability and convenience. If you have any further modifications or need additional features, feel free to ask!