我遇到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_())
答案 0 :(得分: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