串行端口上下文管理器
以下是合理的做法吗?
with SerialPorts() as serial_ports:
in= SerialPort("COM1")
serial_ports.add(in)
out = SerialPort("COM2")
serial_ports.add(out)
# use in and out
其中 SerialPorts
和 SerialPort
实现上下文管理器接口。
SerialPorts.exit()
循环调用其 exit()
添加的串行端口。 SerialPort
的 exit()
关闭串行端口。
有更好的方法吗?
Is the following a reasonable approach?
with SerialPorts() as serial_ports:
in= SerialPort("COM1")
serial_ports.add(in)
out = SerialPort("COM2")
serial_ports.add(out)
# use in and out
where SerialPorts
and SerialPort
implement the context manager interface.
SerialPorts.exit()
loops through the added serial ports calling their exit()
. SerialPort
's exit()
closes the serial port.
Is there a better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果运行此代码:
您将看到两个
__exit__
都会被调用,即使其中一个引发错误(在B
之前使用A
和 <代码>B在A
之前)。如果您从单个集合
__exit__
调用两个__exit__
,如果第一个有错误,则不会调用第二个__exit__
。假设您有少量固定数量的上下文管理器,请改用嵌套上下文管理器。
If you run this code:
you will see that both
__exit__
s get called even if one raises an error (with eitherA
beforeB
andB
beforeA
).If you call both
__exit__
s from a single collective__exit__
, if the first has an error the second__exit__
won't get called.Use nested context managers instead, assuming you have a small fixed number of them.
这个怎么样?
in
是 python 中的保留字,并且使用它作为变量名将导致语法错误。编辑:这是一种可能的实现(未经测试):
但我在这一点上遵循@agf。他的建议更适合你的情况。
How about this?
in
is a reserved word in python, and using it as a variable name will result in a SyntaxError.Edit: Here's one possible implementation (untested):
But I defer to @agf on this one. His suggestion is much better for your case.