简体   繁体   English

Python 协程(Asyncio) - 如何?

[英]Python Coroutine(Asyncio) - How to?

Let's say I want to print "Main" before printing "Foo" .假设我想在打印"Foo"之前打印"Main" " 。 In Lua, it can be achieved with this code:在Lua中,可以用这段代码实现:

local function sleep(sec)
    local start_sleep = os.clock()
    while os.clock() - start_sleep <= sec do
    end
end

local function foo()
    sleep(2)
    print("Foo")
end

local function main()
    coroutine.wrap(foo)()
    print("Main")
end

main()

--[[ 

// Output:

Main
-- waits 2 seconds
Foo

]]

But if I try to implement it in Python it does:但是,如果我尝试在 Python 中实现它,它会:

import asyncio

async def foo():
    await asyncio.sleep(2)
    print("Foo")

def main():
    asyncio.run(foo())
    print("Main")

main()

"""
// Output:

-- waits 2 seconds
Foo
Main

"""

As I am really a beginner at Python, I would like to know how could I achieve it with Python.因为我真的是 Python 的初学者,所以我想知道如何使用 Python 实现它。

Use asyncio.gather() to run coroutines cuncurrently:使用asyncio.gather()同时运行协程:

from asyncio import gather, run, sleep


async def aprint(*args, **kwargs):
    return print(*args, **kwargs)


async def foo():
    await sleep(2)
    await aprint("Foo")

async def main():
    await gather(
        foo(),
        aprint("Main")
    )

run(main())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM