0

我对从线程内部调用时不等待的 subprocess.call() 有问题。

这是我正在使用的代码:

import time
from PyQt4 import QtCore, QtGui
import sys
import subprocess


def tt_fun():
    for a in range(1, 200):
        print  a
##        time.sleep(0.13)
        subprocess.call("timeout 1000")

class SleepProgress(QtCore.QThread):
    procDone = QtCore.pyqtSignal(bool)
    partDone = QtCore.pyqtSignal(int)

    func = None

    def write(self, txt):

        if txt != '':
            try:
                self.partDone.emit(int(txt[:-1]))
            except:pass
    def run(self):
        self.func()
        self.procDone.emit(True)


class AddProgresWin(QtGui.QWidget):
    def __init__(self, func , parent=None ):
        super(AddProgresWin, self).__init__(parent)

        sp =SleepProgress()
        self.thread = sp
        sys.stdout=sp
        self.nameLabel = QtGui.QLabel("0.0%")
        self.nameLine = QtGui.QLineEdit()

        self.progressbar = QtGui.QProgressBar()
        self.progressbar.setMinimum(1)
        self.progressbar.setMaximum(100)

        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(self.progressbar, 0, 0)
        mainLayout.addWidget(self.nameLabel, 0, 1)

        self.setLayout(mainLayout)
        self.setWindowTitle("Processing")
        self.thread.func =func
        self.thread.partDone.connect(self.updatePBar)
        self.thread.procDone.connect(self.fin)

        self.thread.start()

    def updatePBar(self, val):
        self.progressbar.setValue(val)
        perct = "{0}%".format(val)
        self.nameLabel.setText(perct)

    def fin(self):
        pass


if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.path)
    pbarwin = AddProgresWin(tt_fun)
    pbarwin.show()
    sys.exit(app.exec_())
4

1 回答 1

2

subprocess.call("timeout 1000")失败,“没有这样的文件或目录”。您要么需要通过 shell 运行它,subprocess.call("timeout 1000", shell=True)要么将程序和参数作为列表传递subprocess.call(["timeout", " 1000"])。第二个选项会快一点。

在线程中记录错误是个好主意,这样您就知道会发生什么!

def tt_fun():
    try:
        for a in range(1, 200):
            print  a
##            time.sleep(0.13)
            retval = subprocess.check_call("timeout 1000")
    except Exception, e:
        sys.stderr.write("tt_fun error %s\n" % e)
        raise
于 2013-10-21T17:52:40.163 回答