串行端口上下文管理器

发布于 2024-12-12 00:30:48 字数 429 浏览 5 评论 0原文

以下是合理的做法吗?

with SerialPorts() as serial_ports:
    in= SerialPort("COM1")
    serial_ports.add(in)
    out = SerialPort("COM2")
    serial_ports.add(out)

    # use in and out

其中 SerialPortsSerialPort 实现上下文管理器接口。

SerialPorts.exit() 循环调用其 exit() 添加的串行端口。 SerialPortexit() 关闭串行端口。

有更好的方法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绮烟 2024-12-19 00:30:48

如果运行此代码:

class A(object):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        print "exit", self

class B(object):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        print "exit", self
        raise Exception

with A() as a, B() as b:
    pass

您将看到两个 __exit__ 都会被调用,即使其中一个引发错误(在 B 之前使用 A 和 <代码>B在A之前)。

如果您从单个集合 __exit__ 调用两个 __exit__,如果第一个有错误,则不会调用第二个 __exit__

假设您有少量固定数量的上下文管理器,请改用嵌套上下文管理器。

If you run this code:

class A(object):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        print "exit", self

class B(object):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        print "exit", self
        raise Exception

with A() as a, B() as b:
    pass

you will see that both __exit__s get called even if one raises an error (with either A before B and B before A).

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.

纵情客 2024-12-19 00:30:48

这个怎么样?

with SerialPorts("COM1", "COM2") as (inport, outport):
    # use inport and outport

in 是 python 中的保留字,并且使用它作为变量名将导致语法错误。


编辑:这是一种可能的实现(未经测试):

import serial
from contextlib import contextmanager 

@contextmanager
def serial_ports(*args):
    ports = [serial.Serial(arg) for arg in args]
    try:
        yield ports
    finally:
        for port in ports:
            port.close()

with serial_ports('COM1', 'COM2') as (inp, outp):
    print 'inp:', inp.isOpen(), 'outp:', outp.isOpen()

print 'inp:', inp.isOpen(), 'outp:', outp.isOpen()

但我在这一点上遵循@agf。他的建议更适合你的情况。

How about this?

with SerialPorts("COM1", "COM2") as (inport, outport):
    # use inport and outport

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):

import serial
from contextlib import contextmanager 

@contextmanager
def serial_ports(*args):
    ports = [serial.Serial(arg) for arg in args]
    try:
        yield ports
    finally:
        for port in ports:
            port.close()

with serial_ports('COM1', 'COM2') as (inp, outp):
    print 'inp:', inp.isOpen(), 'outp:', outp.isOpen()

print 'inp:', inp.isOpen(), 'outp:', outp.isOpen()

But I defer to @agf on this one. His suggestion is much better for your case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文