假设我有一个threading.Lock()我想要获取的对象以便使用资源.假设我想try ... except ...在资源中使用一个子句.
有几种方法可以做到这一点.
方法1
import threading
lock = threading.Lock()
try:
with lock:
do_stuff1()
do_stuff2()
except:
do_other_stuff()
Run Code Online (Sandbox Code Playgroud)
如果在do_stuff1()或期间发生错误do_stuff2(),是否会释放锁定?或者使用以下方法之一是否更好?
方法2
with lock:
try:
do_stuff1()
do_stuff2()
except:
do_other_stuff()
Run Code Online (Sandbox Code Playgroud)
方法3
lock.acquire():
try:
do_stuff1()
do_stuff2()
except:
do_other_stuff()
finally:
lock.release()
Run Code Online (Sandbox Code Playgroud)
即使发生错误,哪种方法最适合释放锁?
我知道如何获取文本的宽度:
import matplotlib.pyplot as plt
from matplotlib.patches import BoxStyle
xpos, ypos = 0, 0
text = 'blah blah'
boxstyle = BoxStyle("Round", pad=1)
props = {'boxstyle': boxstyle,
'facecolor': 'white',
'linestyle': 'solid',
'linewidth': 1,
'edgecolor': 'black'}
textbox = plt.text(xpos, ypos, text, bbox=props)
plt.show()
textbox.get_bbox_patch().get_width() # 54.121092459652573
Run Code Online (Sandbox Code Playgroud)
但是,这并没有考虑到填充。事实上,如果我将填充设置为 0,我会得到相同的宽度。
boxstyle = BoxStyle("Round", pad=0)
props = {'boxstyle': boxstyle,
'facecolor': 'white',
'linestyle': 'solid',
'linewidth': 1,
'edgecolor': 'black'}
textbox = plt.text(xpos, ypos, text, bbox=props)
plt.show()
textbox.get_bbox_patch().get_width() # 54.121092459652573
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何获得周围框的宽度?或者在 FancyBoxPatch 的情况下如何获得填充的大小?