为了防止上下文切换,我想创建一个大循环来服务于网络连接和一些 routine .

以下是正常功能的实现:

import asyncio
import time


def hello_world(loop):
    print('Hello World')
    loop.call_later(1, hello_world, loop)

def good_evening(loop):
    print('Good Evening')
    loop.call_later(1, good_evening, loop)

print('step: asyncio.get_event_loop()')
loop = asyncio.get_event_loop()

print('step: loop.call_soon(hello_world, loop)')
loop.call_soon(hello_world, loop)
print('step: loop.call_soon(good_evening, loop)')
loop.call_soon(good_evening, loop)

try:
    # Blocking call interrupted by loop.stop()
    print('step: loop.run_forever()')
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print('step: loop.close()')
    loop.close()

以下是协同程序的实现:

import asyncio


@asyncio.coroutine
def hello_world():
    while True:
        yield from asyncio.sleep(1)
        print('Hello World')

@asyncio.coroutine
def good_evening():
    while True:
        yield from asyncio.sleep(1)
        print('Good Evening')

print('step: asyncio.get_event_loop()')
loop = asyncio.get_event_loop()
try:
    print('step: loop.run_until_complete()')
    loop.run_until_complete(asyncio.wait([
        hello_world(),
        good_evening()
    ]))
except KeyboardInterrupt:
    pass
finally:
    print('step: loop.close()')
    loop.close()

混合的一个:

import asyncio
import time


def hello_world(loop):
    print('Hello World')
    loop.call_later(1, hello_world, loop)

def good_evening(loop):
    print('Good Evening')
    loop.call_later(1, good_evening, loop)

@asyncio.coroutine
def hello_world_coroutine():
    while True:
        yield from asyncio.sleep(1)
        print('Hello World Coroutine')

@asyncio.coroutine
def good_evening_coroutine():
    while True:
        yield from asyncio.sleep(1)
        print('Good Evening Coroutine')

print('step: asyncio.get_event_loop()')
loop = asyncio.get_event_loop()

print('step: loop.call_soon(hello_world, loop)')
loop.call_soon(hello_world, loop)
print('step: loop.call_soon(good_evening, loop)')
loop.call_soon(good_evening, loop)
print('step: asyncio.async(hello_world_coroutine)')
asyncio.async(hello_world_coroutine())
print('step: asyncio.async(good_evening_coroutine)')
asyncio.async(good_evening_coroutine())

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print('step: loop.close()')
    loop.close()

如您所见,每个协程函数都有一个while循环.我怎样才能让它像正常的一样?也就是说,当它完成时,在给定的延迟时间后调用自己,但不只是在那里放一个循环.

推荐答案

如果您真的想从协程中消除while循环(我不知道为什么您觉得这是必要的;这是做您想做的事情的最自然的方式),您可以使用asyncio.async(或Python 3.4.4+上的asyncio.ensure_future)来安排协程在下一个事件循环迭代中再次运行:

import asyncio

@asyncio.coroutine
def hello_world():
    yield from asyncio.sleep(1)
    print('Hello World')
    asyncio.async(hello_world())

@asyncio.coroutine
def good_evening():
    yield from asyncio.sleep(1)
    print('Good Evening')
    asyncio.async(good_evening())

print('step: asyncio.get_event_loop()')
loop = asyncio.get_event_loop()
try:
    print('step: loop.run_until_complete()')
    asyncio.async(hello_world())
    asyncio.async(good_evening())
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print('step: loop.close()')
    loop.close()

请注意,如果这样做,您必须切换回使用loop.run_forever(),因为hello_world/good_evening将在打印后立即退出.

Python-3.x相关问答推荐

根据收件箱内部的值以行降序的特定顺序重新排序列

为什么打印语句在Python多处理脚本中执行两次?

如何使用PySide6创建切换框架?

如何从枚举中获取某个值?

Pandas -我们如何在一行中应用多个要求

如何将参数/值从测试方法传递给pytest的fixture函数?

在Python中基于组/ID将两个数据帧进行映射,找出较接近的值

基于Pandas列动态创建分箱,以使观测值数量或计数占总计数的1%.

如何沿单列获取嵌套列表中的唯一值?

如何使用`re.findall`从字符串中提取数据

列出相同索引的Pandas

有没有办法使用 python opencv 计算与图像的白色距离

用于 BIG 数组计算的多处理池映射比预期的要慢

在 Python 3.5 中使用 aiohttp 获取多个 url

如何调试垂死的 Jupyter Python3 内核?

Python 3 与 Python 2 映射行为

在python中,如果一个函数没有return语句,它会返回什么?

Python在OrderedDict中 Select 第i个元素

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

如何从 Base64 转换为字符串 Python 3.2