Any flaw in the logic of using qtimer and qthread?
I have a GUI developed using pyqt4 which has a run button. on run button click, I invoke a timer and a thread. the timer keeps monitoring the thread. on the thread I invoke a command prompt to execute the test cases. I want the thread to be alive till the command prompt is opened and want to say it as dead once I close the command prompt.
The code that I had written to achieve this is as below. Any logic flaws? or any better way to achieve this?
self.connect(self.run_button, SIGNAL('clicked()'), self.runscript)
def runscript(self):
self.timer = QTimer()
self.timer.connect(self.timer, SIGNAL("timeout()"),self.sendData)
self.timer.start(1000)
def sendData(self):
if self.run_timer:
run_mon开发者_运维知识库itor_object = RunMonitor()
print 'Starting the thread...........'
run_monitor_object.start()
self.run_timer = False
if run_monitor_object.isAlive():
print 'Thread Alive...'
else:
print 'Thread is Dead....'
class RunMonitor(threading.Thread):
def __init__(self, parent=None):
threading.Thread.__init__(self)
def run(self):
print 'Invoking Command Prompt..........'
subprocess.call(["start", "/DC:\\Scripts", "scripts_to_execute.bat"], shell=True)
When I run this, I get the following error...
UnboundLocalError: local variable 'run_monitor_object' referenced before assignment at if run_monitor_object.isAlive():
Just wondering how else, I could
This code:
if self.run_timer:
run_monitor_object = RunMonitor()
print 'Starting the thread...........'
run_monitor_object.start()
self.run_timer = False
if run_monitor_object.isAlive():
print 'Thread Alive...'
else:
print 'Thread is Dead....'
Is wrong. If the first branch isn't taken (perhaps in a second invocation when self.run_timer
is already True), run_monitor_object
isn't assigned, and you attempt to use it in the second if
.
To make this work, make run_monitor_thread
an instance variable of the class.
Also, why start the thread in the timer? This is just needlessly complicating your logic. Start it when you create the timer. The timer will then be used to monitor it.
精彩评论