gpt4 book ai didi

python - eventlet是否为线程模块做了monkey_patch?

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:44 24 4
gpt4 key购买 nike

文档位于 http://eventlet.net/doc/patching.htm说“如果没有指定参数,则所有内容都会被修补。”和“线程,用于修补线程、线程和队列”。

但是通过一个简单的测试:

#!/bin/env python

import threading

import eventlet
eventlet.monkey_patch()

if __name__ == '__main__':
patched = eventlet.patcher.is_monkey_patched(threading)
print('patched : %s' % patched)

结果是:

patched : False

线程似乎根本没有修补。文档有误吗?

最佳答案

我发现文档是正确的。问题在于 is_monkey_patched(),它无法检测到某些情况,例如“线程,队列”模块。看一下这个函数的 src,其行为很容易理解。

def _green_thread_modules():
from eventlet.green import Queue
from eventlet.green import thread
from eventlet.green import threading
if six.PY2:
return [('Queue', Queue), ('thread', thread), ('threading', threading)]
if six.PY3:
return [('queue', Queue), ('_thread', thread), ('threading', threading)]
<小时/>
    if on['thread'] and not already_patched.get('thread'):
modules_to_patch += _green_thread_modules()
already_patched['thread'] = True
<小时/>
def is_monkey_patched(module):
"""Returns True if the given module is monkeypatched currently, False if
not. *module* can be either the module itself or its name.

Based entirely off the name of the module, so if you import a
module some other way than with the import keyword (including
import_patched), this might not be correct about that particular
module."""
return module in already_patched or \
getattr(module, '__name__', None) in already_patched

又因为patch操作是这样实现的:

    for name, mod in modules_to_patch:
orig_mod = sys.modules.get(name)
if orig_mod is None:
orig_mod = __import__(name)
for attr_name in mod.__patched__:
patched_attr = getattr(mod, attr_name, None)
if patched_attr is not None:
setattr(orig_mod, attr_name, patched_attr)

我们可以使用以下方法检查像 threading/Queue 这样的模块是否已修补:

 >>>import threading
>>>eventlet.monkey_patch()
>>>threading.current_thread.__module__
>>>'eventlet.green.threading'

关于python - eventlet是否为线程模块做了monkey_patch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com