當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python contextvars.Context.run用法及代碼示例


用法:

run(callable, *args, **kwargs)

在調用run 方法的上下文對象中執行callable(*args, **kwargs) 代碼。如果發生異常,則返回執行結果或傳播異常。

callable 對任何上下文變量所做的任何更改都將包含在上下文對象中:

var = ContextVar('var')
var.set('spam')

def main():
    # 'var' was set to 'spam' before
    # calling 'copy_context()' and 'ctx.run(main)', so:
    # var.get() == ctx[var] == 'spam'

    var.set('ham')

    # Now, after setting 'var' to 'ham':
    # var.get() == ctx[var] == 'ham'

ctx = copy_context()

# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)

# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'

# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'

當從多個 OS 線程對同一上下文對象調用或遞歸調用時,該方法會引發 RuntimeError

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 contextvars.Context.run。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。