线程1中定义的整数变量不希望共享到线程2,UI也不想在简单的循环上更新以更新它。
Main.py
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)
但是,正如您所看到的,整数格式正确并打印到控制台。
答案 0 :(得分:1)
你做的相当于:
#!/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()