1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does 'input()' blocks Python thread?

Discussão em 'Python' iniciado por Stack, Março 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have this tiny code, that takes two functions and runs them asynchrounously. One function uses the input() method for receiving a value from standard input. The other function uses asyncio.sleep().

    import asyncio

    async def in_out():
    for a in range(0, 3):
    x = input("input value: ")
    print(x)

    async def chrono():
    for a in range(0, 3):
    await asyncio.sleep(1)
    print(f"{a} seg.")


    async def main():
    L = await asyncio.gather(
    chrono(),
    in_out(),
    )

    asyncio.run(main())


    When executed, the output is something like:

    input value: a
    a
    input value: b
    b
    input value: c
    c
    0 seg.
    1 seg.
    2 seg.


    My question is, why does the time for sleep, stops while the function input() is blocking the I/O, shouldn't the asyncio execute both functions concurrently?

    Even if the I/O is blocked, I would expect something like:

    input value: a
    a
    0 seg.
    1 seg.
    input value: b
    2 seg.
    b
    input value: c
    c


    I am not asking how can I write a program that does that. That is not my issue. I just want to understand what is going on.

    Continue reading...

Compartilhe esta Página