[英]asyncio event loop equivalent with uvloop
I have an event loop with coroutine method using asyncio
. 我有一个使用asyncio
协程方法的事件循环。
I enthusiast to looking for an equivalent of the following example using uvloop instead. 我热衷于寻找与uvloop相反的以下示例。
Here's a simple asyncio
event loop example: 这是一个简单的asyncio
事件循环示例:
import asyncio
async def read(**kwargs):
oid = kwargs.get('oid', '0.0.0.0.0.0')
time = kwargs.get('time', 1)
try:
print('start: ' + oid)
except Exception as exc:
print(exc)
finally:
await asyncio.sleep(time)
print('terminate: ' + oid)
def event_loop(configs):
loop = asyncio.get_event_loop()
for conf in configs:
asyncio.ensure_future(read(oid=conf['oid'], time=conf['time']))
return loop
if __name__ == '__main__':
snmp_configurations = [
{'time': 5, 'oid': '1.3.6.3.2.4'},
{'time': 6, 'oid': '1.3.6.3.5.8'},
] # TODO :: DUMMY
loop = event_loop(snmp_configurations)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
loop.close()
How to reform the above snippet code by using uvloop ? 如何使用uvloop重新构造上述代码段?
Is the following change correct for using uvloop with more performance? 以下更改是否正确使用具有更高性能的uvloop ?
import uvloop def event_loop(configs): asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # TODO :: uvloop. loop = asyncio.get_event_loop() ` for conf in configs: asyncio.ensure_future(read(oid=conf['oid'], time=conf['time'])) return loop
[ NOTE ]: [ 注意 ]:
Just set event loop policy before you call asyncio.get_event_loop()
. 只需在调用asyncio.get_event_loop()
之前设置事件循环策略asyncio.get_event_loop()
。
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def read(**kwargs):
oid = kwargs.get('oid', '0.0.0.0.0.0')
time = kwargs.get('time', 1)
try:
print('start: ' + oid)
except Exception as exc:
print(exc)
finally:
await asyncio.sleep(time)
print('terminate: ' + oid)
def event_loop(configs):
loop = asyncio.get_event_loop()
for conf in configs:
asyncio.ensure_future(read(oid=conf['oid'], time=conf['time']))
return loop
if __name__ == '__main__':
snmp_configurations = [
{'time': 5, 'oid': '1.3.6.3.2.4'},
{'time': 6, 'oid': '1.3.6.3.5.8'},
] # TODO :: DUMMY
loop = event_loop(snmp_configurations)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
loop.close()
Yes, this code is correct. 是的,此代码正确。 You can set event loop policy after imports. 您可以在导入后设置事件循环策略。
import uvloop
import asyncio
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # TODO :: uvloop.
def event_loop(configs):
loop = asyncio.get_event_loop()
for conf in configs:
asyncio.ensure_future(read(oid=conf['oid'], time=conf['time']))
return loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.