1

Following my previous question. I was advised to make a separate python library and then import it.

After reading a bit more on Stackoverflow, I realized that the best way is to write methods and I've taken up that path.

def USB(port):
        activateme = serial.Serial(port,115200)
        #print "starting to monitor"
        for line in activateme:
                #print line
                return line

def USBprocess(line):
        if line.startswith( '#d'):
                fields = line.split(',')
                if len(fields) > 5:
                        W = fields[1]
                        V = fields[2]
                        A = fields[3]
                print "monitoring"
        return W,V,A

op = USB(port)
w,v,a = USBprocess(op)

and I get the error:

UnboundLocalError: local variable 'W' referenced before assignment

what is it that I am doing wrong?

Community
  • 1
  • 1
pistal
  • 2,310
  • 13
  • 41
  • 65

2 Answers2

6

You should provide values for W, V, A at the start of the function, in case the first if condition is not True. Something like this, perhaps (change for default values appropriate for your problem):

def USBprocess(line):
    W, V, A = '0', '0', '0'
    if line.startswith('#d'):
        # etc.
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

In case this expression is not true:

 line.startswith( '#d')

variables W, V and A will not be initialized in your USBprocess function, so return will fail.

Fix it by initializing all local variables before the if statement.

piokuc
  • 25,594
  • 11
  • 72
  • 102