0

Let's say I want to print "Main" before printing "Foo". In Lua, it can be achieved with this code:

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:

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.

1 Answer 1

1

Use asyncio.gather() to run coroutines cuncurrently:

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())
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.