【问题标题】:Any flaw in the logic of using qtimer and qthread?使用 qtimer 和 qthread 的逻辑有什么缺陷吗?
【发布时间】:2011-08-23 03:06:12
【问题描述】:

我有一个使用 pyqt4 开发的 GUI,它有一个运行按钮。在运行按钮单击时,我调用一个计时器和一个线程。计时器不断监视线程。在线程上,我调用命令提示符来执行测试用例。我希望线程在命令提示符打开之前一直处于活动状态,并且一旦我关闭命令提示符就想说它已经死了。

我为此编写的代码如下。有什么逻辑缺陷吗?或者有什么更好的方法来实现这一点?

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_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....'

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)

当我运行它时,我收到以下错误...

UnboundLocalError:在 if run_monitor_object.isAlive() 赋值之前引用了局部变量“run_monitor_object”:

只是想知道怎么做,我可以

【问题讨论】:

  • 如果您使用 QThread 而不是标准的 Python 线程,您可以将函数连接到它的 finished() 信号。然后,您可以在被调用的函数中运行代码,而不是使用计时器检查线程状态。

标签: python multithreading pyqt pyqt4


【解决方案1】:

这段代码:

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....'

错误。如果第一个分支没有被采用(可能在第二次调用中,self.run_timer 已经为 True),则不会分配 run_monitor_object,并且您尝试在第二个 if 中使用它。

要完成这项工作,请将 run_monitor_thread 设为类的实例变量。

另外,为什么要在计时器中启动线程?这只是不必要地使您的逻辑复杂化。创建计时器时启动它。然后将使用计时器对其进行监控。

【讨论】:

    猜你喜欢
    • 2015-10-19
    • 2017-07-16
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多