Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python硬编码上下文管理器_Python - Fatal编程技术网

Python硬编码上下文管理器

Python硬编码上下文管理器,python,Python,我必须执行一个大致如下的代码: FPGA.send('enter read mode') FPTA.send('read') FPGA.send('exit read mode') with read_mode(): FPGA.send('read mode') 我希望确保无论'read'行中是否存在问题,都会执行'exit read mode'行。在Python中实现这一点最优雅的方法是使用上下文管理器。但是,我不想为这个FPGA对象编写\uuuuuuuuuuuuuuuuuuuuu

我必须执行一个大致如下的代码:

FPGA.send('enter read mode')
FPTA.send('read')
FPGA.send('exit read mode')
with read_mode():
    FPGA.send('read mode')
我希望确保无论
'read'
行中是否存在问题,都会执行
'exit read mode'
行。在Python中实现这一点最优雅的方法是使用上下文管理器。但是,我不想为这个
FPGA
对象编写
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。当我阅读本文时,我想以某种方式“硬编码”这种上下文管理器行为。我认为一个
try
除了
块外,它可以完成以下任务:

FPGA.send('enter read mode')
try:
    FPGA.send('read')
except Exception as e:
    rise e
finally:
    FPGA.send('exit read mode')

但是我想知道是否有一种更具python风格的方法来实现这一点?

contextlib.contextmanager
decorator提供了一个很好的快捷方式来创建上下文管理器对象,这样您就不需要实现
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu enter\uuuuuuuuuuuuuuuuu
方法

from contextlib import contextmanager

@contextmanager
def read_mode():
    FPGA.send('enter read mode')
    try:
        yield
    finally:
        FPGA.send('exit read mode')
然后您可以像这样使用此上下文管理器:

FPGA.send('enter read mode')
FPTA.send('read')
FPGA.send('exit read mode')
with read_mode():
    FPGA.send('read mode')

@contextmanager
函数中的
yield
将控制权交给上下文中的代码块。当上下文退出时(无论是正常退出还是通过引发的异常退出),将执行
finally
块。

contextlib.contextmanager
装饰程序为创建上下文管理器对象提供了一个很好的快捷方式,您无需实现
\uuuuuuuuuuuuuuuuuu\uuuuuuuuuuuuuuuuuuuuu
方法

from contextlib import contextmanager

@contextmanager
def read_mode():
    FPGA.send('enter read mode')
    try:
        yield
    finally:
        FPGA.send('exit read mode')
然后您可以像这样使用此上下文管理器:

FPGA.send('enter read mode')
FPTA.send('read')
FPGA.send('exit read mode')
with read_mode():
    FPGA.send('read mode')

@contextmanager
函数中的
yield
将控制权交给上下文中的代码块。当上下文退出时(无论是正常还是通过引发的异常),执行
finally
块。

为什么您认为try/except/finally不是pythonic?上面说-
这允许封装常见的try…except…finally使用模式以方便重用。
因此编写上下文管理器似乎也是pythonic的,但您拒绝将其作为一个选项。顺便注意,您不需要作为e:raise e执行
异常除外--raise e基本上是不可操作的,因为未捕获的异常已经出现了。为什么您认为try/except/finally不是pythonic呢?上面说-
这允许封装常见的try…except…finally使用模式以方便重用。
因此编写上下文管理器似乎也是如此Pythonic,但您已拒绝将其作为一个选项。顺便说一句,您不需要执行
,除非异常为e:raise e
——这基本上是不可操作的,因为未捕获的异常将已经引发。