什么时候在 Pyserial 中使用 close() 和 __del__()?

When to use close() and __del__() in Pyserial?

根据documentation,class serial.Serial()有以下方法。

close()
Close port immediately.

__del__()
Destructor, close port when serial port instance is freed.

我想知道什么时候应该使用close()__del__()?例如,我有一个 GUI,它创建了一个 serial.Serial() 的实例,并分配了一个端口。根据文档,分配的端口将在实例 serial.Serial() 时打开。现在,当我终止我的 GUI 时,我说 __del__()(而不是 close())是关闭串口最合适的方法是否正确?

分析

如果我们查看 pyserial source,我们会看到:

class SerialBase(io.RawIOBase):

啊哈!让我们看看 io.RawIOBase:

Base class for raw binary I/O. It inherits IOBase. There is no public constructor.

好的。在 IOBase 中寻找 __del__ 我们看到:

__del__() Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.

结论

您可以使用 close()delwith-context - 它们都会关闭端口。