2013-07-28 153 views
6

进出口新Python和编程,但不能Python的全局变量似乎明白了为什么这个功能不会更新全局变量没有更新

global weight 
weight = 'value' 
def GetLiveWeight(): 
    SetPort() 
    while interupt == False: 
     port.write(requestChar2) 
     liveRaw = port.read(9) 
     liveRaw += port.read(port.inWaiting()) 
     time.sleep(0.2) 
     weight = liveRaw.translate(None, string.letters) 
    return weight 

我也试过这种

weight = 'value' 
def GetLiveWeight(): 
    global weight 
    SetPort() 
    while interupt == False: 
     port.write(requestChar2) 
     liveRaw = port.read(9) 
     liveRaw += port.read(port.inWaiting()) 
     time.sleep(0.2) 
     weight = liveRaw.translate(None, string.letters) 
    return weight 

try: 
    threading.Thread(target = GetLiveWeight).start() 
    print liveWeight 
except: 
    print "Error: unable to start thread" 

回答

12

您需要声明那weight是全球里面GetLiveWeight,不在它之外。

weight = 'value' 
def GetLiveWeight(): 
    global weight 

global statement告诉Python的GetLiveWeight功能的范围内,weight指的是全局变量weight,而不是一些新的局部变量weight

+1

谢谢我已经尝试过,但我似乎无法获得改变重量变量的功能,它似乎总是保持设置值? – Rhys

+1

你确定'interupt == False'(通常写成'not interupt')的条件是否为真?换句话说,你确定'while循环'内的代码是否正在执行? – unutbu

+0

是的,我在while循环中添加了一个打印输出变量重量,它工作正常。这可能与我称为它的方式有关'尝试: threading.Thread(target = GetLiveWeight).start() print liveWeight 除外: 打印“错误:无法启动线程”' – Rhys