code not working, NameError: name 's' is not defined - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: code not working, NameError: name 's' is not defined (/thread-30108.html) |
code not working, NameError: name 's' is not defined - ridgerunnersjw - Oct-05-2020 Good afternoon.... I have a serial device that I am able to communicate with. I decided to put the code into a class module and build it out. I am running into an issue with respect to the serial port.... My code: #! /usr/bin/python class RD(): '''RFB K-LD2 module''' def __init__(self, command): '''initialize''' self.cmd = command from serial import Serial s = Serial('/dev/ttyS0', 38400) def KLD2Setup(self): '''use this method for sending commands and receiving data''' self.cmd = '$' + self.cmd + '\r' if (self.cmd[1] in {"S","D","R","W","T"}): k = 8 elif (self.cmd[1] in {"F","A"}): k = 10 elif (self.cmd[1] == "C"): k = input ("Enter the number of bytes? ") else: k = 0 if (k): s.write(self.cmd.encode()) print((s.read(int(k)).rstrip()).lstrip(b'@'))This code block works if I invoke python create a serial port, etc. in a file without a class RE: code not working..... - Larz60+ - Oct-05-2020 this is a scope issue, change:
RE: code not working..... - Yoriz - Oct-05-2020 In the __init__ you create a local s and try to use a local s in the method KLD2Setup As you are now using a class you need to use self.s #! /usr/bin/python from serial import Serial class RD(): '''RFB K-LD2 module''' def __init__(self, command): '''initialize''' self.cmd = command self.s = Serial('/dev/ttyS0', 38400) def KLD2Setup(self): '''use this method for sending commands and receiving data''' self.cmd = '$' + self.cmd + '\r' if (self.cmd[1] in {"S","D","R","W","T"}): k = 8 elif (self.cmd[1] in {"F","A"}): k = 10 elif (self.cmd[1] == "C"): k = input ("Enter the number of bytes? ") else: k = 0 if (k): self.s.write(self.cmd.encode()) print((self.s.read(int(k)).rstrip()).lstrip(b'@')) RE: code not working..... - ridgerunnersjw - Oct-05-2020 Thank you both very much...That worked great! RE: code not working, NameError: name 's' is not defined - buran - Oct-05-2020 just to mention that brackets in your if/elif/else conditions are redundant if self.cmd[1] in {"S","D","R","W","T"}: k = 8 elif self.cmd[1] in {"F","A"}: k = 10 elif self.cmd[1] == "C": k = input("Enter the number of bytes? ") else: k = 0 if k: |