簡體   English   中英

Python; 無法共享變量並在線程之間更新Qt GUI

[英]Python ; Cant share variable and update Qt GUI between threads

線程1中定義的整數變量不希望與線程2共享,UI也不想在簡單的循環上進行更新以對其進行更新。

主程序

from ui import Ui_main_window
from PyQt4 import QtGui, QtCore

import sys
import subprocess
import commands
import threading

class MainWindow(QtGui.QMainWindow, Ui_main_window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

def _dd_thread_run(_if, _of, _bs, _size):
    _dd_subprocess_command_format = "dd if=%s bs=%s | pv -n --size %s | dd of=%s" % (_if, _bs, _size, _of)
    _dd_subprocess_command = [_dd_subprocess_command_format]
    _dd_progress = subprocess.Popen(_dd_subprocess_command, shell=True, stderr=subprocess.PIPE)
    while _dd_progress.poll() is None:
        out = _dd_progress.stderr.readline().replace("\n", "")
        out_int = int (out)
        print "[DEBUG] %r" % out_int

def _dd_do():
    _dd_thread_run("/dev/urandom", "/dev/null", "100K", "100M")

def _ui_progress_set():
    while True:
        for i in range(0, 100):
            ui2 = MainWindow()
            ui2.progressBar.setValue(i) # < Not working, does nothing, no error
            print out_int # < Throws error, "not defined"


app = QtGui.QApplication(sys.argv)

ui = MainWindow()
ui.show()

t1 = threading.Thread(target=_dd_do, args=[])
t1.start()

t2 = threading.Thread(target=_ui_progress_set, args=[])
t2.start()

sys.exit(app.exec_())

該程序非常簡單直接。 我錯過了什么嗎? 如何處理在線程之間使用的全局變量?

啟動第二個線程后,它立即引發未定義out_int的錯誤。

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "untitled3.py", line 55, in _ui_progress_set
    print out_int
NameError: global name 'out_int' is not defined

[DEBUG] 12
[DEBUG] 25
[DEBUG] 38
[DEBUG] 52
[DEBUG] 65
[DEBUG] 79
[DEBUG] 92
[DEBUG] 94

雖然是,但在這里: out_int = int (out)

但是,如您所見,該整數已正確格式化並打印到控制台。

您所做的等同於:

#!/usr/bin/python

def first() :
  out_int = 1


def second() :
  print out_int

first()
second()

結果是:

Traceback (most recent call last):
  File "./test.py", line 12, in <module>
    second()
  File "./test.py", line 8, in second
    print out_int
NameError: global name 'out_int' is not defined

因此,您必須在全局范圍內定義out_int ,並在修改函數中聲明要訪問該全局變量。

解決方案如下:

#!/usr/bin/python

out_int = 0

def first() :
  global out_int
  out_int = 1


def second() :
  print out_int

first()
second()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM