subprocess.call()从线程调用时不要等待

2024-09-30 08:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题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_())

Tags: importselftxtdefsysthreadfuncsubprocess
1条回答
网友
1楼 · 发布于 2024-09-30 08:32:07

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

相关问题 更多 >

    热门问题