Advertisement
Guest User

pyqt subprocess stdin

a guest
Mar 4th, 2022
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. import sys
  2. import subprocess
  3. from PyQt6 import QtWidgets, uic
  4. from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot, QThread
  5.  
  6.  
  7. class Action(QObject):
  8.     runProcess = pyqtSignal(str)
  9.  
  10.     @pyqtSlot()
  11.     def RunProcess(self):
  12.         self.process = subprocess.Popen(["nmap\\ncat.exe", "-lvkp", "666"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
  13.                                    creationflags=0x08000000, universal_newlines=True, encoding="utf8", errors="ignore")
  14.  
  15.         self.i = 0
  16.         while (True):
  17.             if self.process.poll() is None:
  18.                 output = self.process.stdout.readline()
  19.                 print(output)  # for debugging
  20.                 prettyOutput = output
  21.                 window.chat_console.insertPlainText(prettyOutput)
  22.                 QtWidgets.QApplication.processEvents()
  23.  
  24.             else:  # if the process is dead it breaks the loop
  25.                 break
  26.             print(self.i)  # debug
  27.             self.i = self.i + 1
  28.  
  29.  
  30. class MainWindow(QtWidgets.QMainWindow):
  31.     def Send(self):
  32.         print("tried to write into stdin")
  33.         self.action.process.stdin.writelines("test\n")  # trying to write to stdin
  34.         self.action.process.stdin.flush()  # hoping that flush would write
  35.  
  36.     def __init__(self, *args, **kwargs):
  37.         super().__init__(*args, **kwargs)
  38.         uic.loadUi(f"gui.ui", self)
  39.  
  40.         self.show()
  41.  
  42.         self.action = Action()
  43.         self.thread = QThread(self)
  44.         self.action.runProcess.connect(Action.RunProcess)
  45.         self.action.moveToThread(self.thread)
  46.         self.thread.started.connect(self.action.RunProcess)
  47.         self.thread.start()
  48.  
  49.         self.send_button.clicked.connect(lambda: self.Send())
  50.  
  51.     def closeEvent(self, event):
  52.         y = self.action.i  # saves the number of the current loop
  53.         self.action.process.terminate()  # kills the subprocess
  54.         while(True):  # make the program wait and not quit too early
  55.             if self.action.i > y:  # checks if the current loop number is higher than saved
  56.                 self.thread.terminate()  # kills the thread if the loop stopped
  57.                 exit()  # nicely ends the process
  58.  
  59.  
  60. app = QtWidgets.QApplication(sys.argv)
  61. window = MainWindow()
  62. app.exec()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement