【问题标题】:subprocess.call() do not wait when called from threadsubprocess.call() 从线程调用时不等待
【发布时间】:2013-10-21 17:21:48
【问题描述】:

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

【问题讨论】:

  • 您预计会发生什么,但会发生什么?另外,你确定你真的在运行任何东西吗?您只是在使用 call 而不检查返回值。
  • 这段代码显示了一个进度条,我已经设置了超时来延迟progrssbar值的每次更改,但是这个“超时”似乎被忽略了。所以线程不要等待超时完成

标签: python multithreading python-2.7 subprocess


【解决方案1】:

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

【讨论】:

  • 使用check_call 可能比使用callassert 更简单。除了更短之外,这意味着您会得到一种有意义的异常类型,而不是 AssertionError
  • @abarnet - 是的,你是对的。我试图强调返回代码检查的必要性,但这是一种更好的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2019-06-07
  • 2012-04-14
相关资源
最近更新 更多