24

I'm new with Python and programming but I can't seem to understand why this function does not update the global variable

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

I also tried this:

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"

1 Answer 1

31

You need to declare that weight is global inside GetLiveWeight, not outside it.

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

The global statement tells Python that within the scope of the GetLiveWeight function, weight refers to the global variable weight, not some new local variable weight.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I had tried that, but still I cannot seem to get the function to change the weight variable it always seems to stay set to value?
Are you sure the condition interupt == False (which is more commonly written as not interupt) is ever True? In other words, are you sure the code inside the while-loop is getting executed?
yes, I added a print into the while loop to output the variable weight and it works fine. It may have something to do with the way that I am calling it 'try: threading.Thread(target = GetLiveWeight).start() print liveWeight except: print "Error: unable to start thread"'
The print statement inside the try-suite is getting executed before the other thread modifies weight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.