简体   繁体   中英

Unable to compile and return for a Python function, in a try-except structure

I did debug the code below, line-by-line using some print statements.

class Timeout(Exception):
    pass

def getSource(comm):
    source = comm.split('@')
    params = source[1].split(':')
    debug = '--debug' in sys.argv
    if source[0] == 'serial':
        try:
            return Serial(params[0], int(params[1]), flush=True, debug=debug)
        except:
            print ("ERROR: Unable to initialize a serial connection to", comm)
            raise Exception

Everything looks OK until the line:

return Serial(params[0], int(params[1]), flush=True, debug=debug)

this line is supposed to be compiled since all the objects in the Serial like params[0] , etc are obtained. But it returns an error jumping to the except and printing the statement "ERROR: Unable to initialize a serial connection to ..."

I am using Python 3.6.8 on a Docker container.

Any kind of help would be appreciated. I'm ready for any further info, if needed.

Here, I post the Serial . I hope this helps you guys to better understand my issue.

class Serial:

def __init__(self, port, baudrate, flush=False, debug=False, readTimeout=None, ackTimeout=0.02):
    self.debug = debug
    self.readTimeout = readTimeout
    self.ackTimeout = ackTimeout
    self._ts = None

    if port.startswith('COM') or port.startswith('com'):
        port = int(port[3:]) - 1
    elif port.isdigit():
        port = int(port) - 1

    self._s = serial.Serial(port, int(baudrate), rtscts=0, timeout=0.5)
    self._s.flushInput()
    if flush:
        print >>sys.stdout, "Flushing the serial port",
        endtime = time.time() + 1
        while time.time() < endtime:
            self._s.read()
            sys.stdout.write(".")
        if not self.debug:
            sys.stdout.write("\n")
    self._s.close()
    self._s = serial.Serial(port, baudrate, rtscts=0, timeout=readTimeout)

def getByte(self):
    c = self._s.read()
    if c == '':
        raise Timeout
    #print 'Serial:getByte: 0x%02x' % ord(c)
    return ord(c)

def putBytes(self, data):
    #print "DEBUG: putBytes:", data
    for b in data:
        self._s.write(struct.pack('B', b))
        time.sleep(0.000001)

def getTimeout(self):
    return self._s.timeout

def setTimeout(self, timeout):
    self._s.timeout = timeout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM