如何正确管理串行资源?[Python]

如何正确管理串行资源?[Python],python,memory,resources,Python,Memory,Resources,我正在用python和Arduino进行一个自动化项目。我需要运行一个测试,确保Arduino已连接(而不是其他设备)。我有一个简单的测试用例,它可以工作,但根本不管理串行对象的内存。我有一个解决方案,我觉得应该工作,但它会导致串行连接问题。结果是第一次读取返回一个空字符串。后续读取返回正确的值。对于我的应用程序,我需要它在第一次尝试时正确阅读 这是我使用的测试代码。这段代码运行得很好(这就是我如何知道问题不在Arduino方面的原因) 这是我试图创建一种更好的方法来使用上下文管理器和with语

我正在用python和Arduino进行一个自动化项目。我需要运行一个测试,确保Arduino已连接(而不是其他设备)。我有一个简单的测试用例,它可以工作,但根本不管理串行对象的内存。我有一个解决方案,我觉得应该工作,但它会导致串行连接问题。结果是第一次读取返回一个空字符串。后续读取返回正确的值。对于我的应用程序,我需要它在第一次尝试时正确阅读

这是我使用的测试代码。这段代码运行得很好(这就是我如何知道问题不在Arduino方面的原因)

这是我试图创建一种更好的方法来使用上下文管理器和with语句管理串行资源。我试了两件事。ArduinoWith类只返回false(并打印空字符串),不指示Arduino上的任何输入。ArduinoSelf第一次得到相同的结果,但第二次返回True

import serial
import time
from contextlib import contextmanager

@contextmanager
def arduino_serial_connection(path, rate, timeout=1):
    connection = serial.Serial(path, rate, timeout=timeout)
    yield connection
    connection.close()

class ArduinoWith:
    def __init__(self):
        pass

    def connection_test(self):
        try:
            with arduino_serial_connection('/dev/tty.usbmodem14101', 9600) as connection:
                connection.write(b"S\n")
                time.sleep(0.2)
                answer = connection.readline().decode('utf-8').rstrip()#connection.read(8)
                if answer == "H":
                    return True
                else:
                    print("Answer: \"" + answer +"\"")
        except serial.serialutil.SerialTimeoutException:
            print("Timeout")
        except Exception:
           print("Execption")
        return False

class ArduinoSelf:
    def __init__(self):
        self.ser = serial.Serial('/dev/tty.usbmodem14101', 9600, timeout=1)

    def connection_test(self):
        try:
            self.ser.write(b"S\n")
            time.sleep(0.2)
            answer = self.ser.readline().decode('utf-8').rstrip()#connection.read(8)
            if answer == "H":
                return True
            else:
                print("Answer: \"" + answer +"\"")
        except serial.serialutil.SerialTimeoutException:
            print("Timeout")
        except Exception:
           print("Execption")
        return False


a1 = ArduinoWith()
print(a1.connection_test())
time.sleep(1)
a2 = ArduinoSelf()
print(a2.connection_test())
time.sleep(1)
print(a2.connection_test())
我不太清楚为什么在ArduinoSelf类上再次运行该方法是有效的,但它确实起了作用,这让我觉得一定有一些东西我没有正确初始化

import serial
import time
from contextlib import contextmanager

@contextmanager
def arduino_serial_connection(path, rate, timeout=1):
    connection = serial.Serial(path, rate, timeout=timeout)
    yield connection
    connection.close()

class ArduinoWith:
    def __init__(self):
        pass

    def connection_test(self):
        try:
            with arduino_serial_connection('/dev/tty.usbmodem14101', 9600) as connection:
                connection.write(b"S\n")
                time.sleep(0.2)
                answer = connection.readline().decode('utf-8').rstrip()#connection.read(8)
                if answer == "H":
                    return True
                else:
                    print("Answer: \"" + answer +"\"")
        except serial.serialutil.SerialTimeoutException:
            print("Timeout")
        except Exception:
           print("Execption")
        return False

class ArduinoSelf:
    def __init__(self):
        self.ser = serial.Serial('/dev/tty.usbmodem14101', 9600, timeout=1)

    def connection_test(self):
        try:
            self.ser.write(b"S\n")
            time.sleep(0.2)
            answer = self.ser.readline().decode('utf-8').rstrip()#connection.read(8)
            if answer == "H":
                return True
            else:
                print("Answer: \"" + answer +"\"")
        except serial.serialutil.SerialTimeoutException:
            print("Timeout")
        except Exception:
           print("Execption")
        return False


a1 = ArduinoWith()
print(a1.connection_test())
time.sleep(1)
a2 = ArduinoSelf()
print(a2.connection_test())
time.sleep(1)
print(a2.connection_test())