2016-07-23 88 views
0

我有一個PyQt5應用程序需要寫入子進程停止的輸入。爲什麼python Subprocess.stdin.write()kill PyQt Gui

但是它也殺死我的PyQt5 Mainwindow,如果使用輸入按鈕而不先使用子進程按鈕。

如果我先用子鍵,然後用輸入按鈕,與self.bob.stdin.write("b")應用程序保持打開狀態,但如果我先按下輸入按鈕而不按子鍵self.bob.stdin.write("b")它殺死我的應用程序主窗口。

那麼爲什麼self.bob.stdin.write("b")殺應用程序,我如何阻止它殺我的主窗口,如果我先按輸入按鈕?

在這個測試代碼中可以看到兩難。

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

您是否可以將代碼簡化爲最小必需示例來演示問題?這使得它更容易找到問題。 –

+0

刪除了幾行,其最小的應用程序創建,和兩個按鈕的功能 如果你按下左鍵,然後右鍵然後它沒事。 但是,如果你先按左鍵,然後GUI退出 –

回答

1

不理解所有的代碼,這是我覺得你的代碼轉換成腳本的作用:

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") 

我會讓你想想hapens當你不執行步驟1。

+0

是的,這是我的腳本縮小,但問題是,它是一個PyQt Gui的一部分,這就是bob.stdin.write(b「text」)殺死 –

+1

我明白了,因爲它不能在第二步中找到bob,因爲它在第一步.Facepalm thx –

+0

當你做'self.bob'時,你可能會得到'AttributeError'。 (1)將函數包裝在'try ... catch AttributeError'中,(2)在函數的開頭檢查self.bob或者(3)禁用第二個按鈕直到' self.bob'可用。 –