假设您有三个通过上下文管理器获取的对象,例如A锁,数据库连接和ip套接字.您可以通过以下方式获取它
with lock:
with db_con:
with socket:
#do stuff
Run Code Online (Sandbox Code Playgroud)
但有没有办法在一个街区内完成?就像是
with lock,db_con,socket:
#do stuff
Run Code Online (Sandbox Code Playgroud)
此外,如果有一组具有上下文管理器的未知长度的对象,是否有可能以某种方式做到:
a=[lock1, lock2, lock3, db_con1, socket, db_con2]
with a as res:
#now all objects in array are acquired
Run Code Online (Sandbox Code Playgroud)
如果答案是"不",是不是因为需要这样的功能意味着设计不好,或者我应该建议它?:-P
Python 3.4提供了这个简洁的工具来暂时重定向stdout:
# From https://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout
with redirect_stdout(sys.stderr):
help(pow)
Run Code Online (Sandbox Code Playgroud)
代码并不是非常复杂,但我不想一遍又一遍地写它,特别是因为有些想法已经进入它以使它重新进入:
class redirect_stdout:
def __init__(self, new_target):
self._new_target = new_target
# We use a list of old targets to make this CM re-entrant
self._old_targets = []
def __enter__(self):
self._old_targets.append(sys.stdout)
sys.stdout = self._new_target
return self._new_target
def __exit__(self, exctype, excinst, exctb):
sys.stdout = self._old_targets.pop()
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一般方法使用该with语句来临时更改变量的值.从另外两个用例sys是sys.stderr和sys.excepthook.
在一个完美的世界中,这样的东西会起作用:
foo = 10
with 20 as foo:
print(foo) # 20
print (foo) # 10
Run Code Online (Sandbox Code Playgroud)
我怀疑我们能做到这一点,但也许这样的事情是可能的:
foo = 10
with temporary_set('foo', …Run Code Online (Sandbox Code Playgroud)