Storm Shadow
Storm Shadow

Reputation: 462

Why do python Subprocess.stdin.write() kill PyQt Gui

I have a PyQt5 app that need to write input for the subprocess to stop.

However it also kills my PyQt5 Mainwindow, if input button is used without using subprocess button first.

If i use subprocess button first, and then use input button , with self.bob.stdin.write("b") app stays open, but if i press input button first without pressing subprocess button self.bob.stdin.write("b") it kills my app and Mainwindow.

So why do self.bob.stdin.write("b") kill app ,and how do i stop it from killing my MainWindow, if i press input button first ?

The dilemma can be seen in this test code.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(308, 156)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Button_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_2.setGeometry(QtCore.QRect(20, 40, 121, 71))
        self.Button_2.setObjectName("subprocessButton_2")
        self.Button_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_1.setGeometry(QtCore.QRect(170, 40, 121, 71))
        self.Button_1.setObjectName("inputbutton")
        MainWindow.setCentralWidget(self.centralwidget)


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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        self.Button_2.setText(_translate("MainWindow", "subprocess"))
        self.Button_1.setText(_translate("MainWindow", "input"))

        self.Button_2.clicked.connect(self.sub)
        self.Button_1.clicked.connect(self.input)

    def sub(self):

        import subprocess
        from subprocess import Popen, PIPE
        from subprocess import Popen, PIPE
        self.bob = subprocess.Popen('cmd ',stdin=PIPE, shell=True)

    def input(self):
        self.bob.stdin.write("q")


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_())

Upvotes: 0

Views: 322

Answers (1)

Georg Schölly
Georg Schölly

Reputation: 126095

Without understanding all your code, here's what I think your code converted into a script does:

import subprocess
from subprocess import Popen, PIPE

# sub button handler
bob = subprocess.Popen('echo',stdin=PIPE, shell=True)

# input button handler
bob.stdin.write(b"text")

I'll let you think about what hapens when you don't do step 1.

Upvotes: 1

Related Questions