1

Как остановить выполнение subprocess после нажатия кнопки , вот сам код кнопки:

import platform
import subprocess

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_scan_network(object):
    def setupUi(self, scan_network):
        self.pushButton2 = QtWidgets.QPushButton(scan_network)
        self.pushButton2.setGeometry(QtCore.QRect(450, 70, 75, 23))
        self.pushButton2.setObjectName("pushButton")
        self.add_functions()
def retranslateUi(self, scan_network):
    self.pushButton2.setText(_translate("scan_network", "STOP"))

Надо остановить выполнение вот этого метода:

def start_scan(self):
    ip_adress = self.lineEdit_4.text()
    for ping1 in range(1,255):
        address = str(ip_adress) + str(ping1)
        def ping(ipAddr, timeout=100):

            if platform.system().lower() == 'windows':
                numFlag = '-n'
            else:
                numFlag = '-c'
            completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
                                           stdout=subprocess.PIPE,  # Capture standard out
                                           stderr=subprocess.STDOUT)  # Capture standard error
            # print(completedPing.stdout)
            return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)

        print(ping1, address, (ping(address)))

Воспроизводимый пример:

import platform
import subprocess

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(482, 82)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(10, 0, 161, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(310, 0, 161, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 482, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.add_functions()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "START"))
        self.pushButton_2.setText(_translate("MainWindow", "STOP"))

    def add_functions(self):
        self.pushButton.clicked.connect(self.start_scan)



    def start_scan(self):
        ip_adress = '192.168.1.'
        for ping1 in range(1,15):
            address = str(ip_adress) + str(ping1)
            def ping(ipAddr, timeout=100):

                if platform.system().lower() == 'windows':
                    numFlag = '-n'
                else:
                    numFlag = '-c'
                completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
                                               stdout=subprocess.PIPE,  # Capture standard out
                                               stderr=subprocess.STDOUT)  # Capture standard error
                # print(completedPing.stdout)
                return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)

            print(ping1, address, (ping(address)))




if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
2

1 ответ 1

1

Попробуйте так:

import platform
import subprocess
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(482, 82)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(10, 0, 161, 41))
        self.pushButton.setObjectName("pushButton")
#        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
#        self.pushButton_2.setGeometry(QtCore.QRect(310, 0, 161, 41))
#        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 482, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "START"))
#        self.pushButton_2.setText(_translate("MainWindow", "STOP"))


class WorkThread(QtCore.QThread):
    threadSignal = QtCore.pyqtSignal(object, object, object, str)
    finished = QtCore.pyqtSignal(str)
    
    def __init__(self, ip_adress, numFlag, timeout):
        super().__init__()
        self.ip_adress = ip_adress
        self.numFlag = numFlag
        self.timeout = timeout

    def run(self):
        for ping1 in range(1, 15):
            address = f'{self.ip_adress}{ping1}' 

            completedPing = subprocess.run(
                ['ping', self.numFlag, '1', '-w', str(self.timeout), address],
                stdout=subprocess.PIPE,   # Capture standard out
                stderr=subprocess.STDOUT  # Capture standard error
            )
            self.msleep(1)
                
            self.threadSignal.emit(
                completedPing.returncode, 
                b'TTL=' in completedPing.stdout, 
                completedPing.stdout,
                address
            )
        self.finished.emit("Start thread")
        

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        self.pushButton.setText("Start thread")
        self.textEdit = QtWidgets.QTextEdit()
                
        layout = QtWidgets.QGridLayout(self.centralwidget)
        layout.addWidget(self.pushButton, 0, 0)
        layout.addWidget(self.textEdit, 1, 0)
        
        self.pushButton.clicked.connect(self.start_scan)

        if platform.system().lower() == 'windows':
            self.numFlag = '-n'
        else:
            self.numFlag = '-c'
            
        self.timeout = 100    
#        self.ip_adress = '192.168.1.'
        self.ip_adress = '8.8.8.'
        self.thread = None

    def start_scan(self):
        if self.thread is None:
            self.thread = WorkThread(self.ip_adress, self.numFlag, self.timeout)
            self.thread.threadSignal.connect(self.on_threadSignal)
            self.thread.finished.connect(self.thread_finished)
            self.thread.start()
            self.pushButton.setText("Stop thread")
        else:
            self.thread.terminate()
            self.thread = None
            self.pushButton.setText("Start thread")

    def on_threadSignal(self, code, ttl, stdout, address):
        cursor = self.textEdit.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(
            f'\n{address}: code={code}, ttl={ttl} \n{stdout.decode("cp866")} {"="*30}\n'  
        )  
        self.textEdit.ensureCursorVisible()
        
    def thread_finished(self, text):
        self.thread = None
        self.pushButton.setText("Start thread")
        

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(482, 482)
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

введите сюда описание изображения

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.