Skip to content

Question.ask() breaks on already running asyncio loop #439

@ttimasdf

Description

@ttimasdf

Describe the bug

Question.ask() creates a new asyncio event loop and will raise RuntimeError: This event loop is already running if the event loop is already running.

[19:49:38.731] Loading script test.py
[19:49:38.783] error in script test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    questionary.text("What's your first name").ask()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "path\to\.venv\Lib\site-packages\questionary\question.py", line 64, in ask
    return self.unsafe_ask(patch_stdout)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
  File "path\to\.venv\Lib\site-packages\questionary\question.py", line 89, in unsafe_ask
    return self.application.run()
           ~~~~~~~~~~~~~~~~~~~~^^
  File "path\to\.venv\Lib\site-packages\prompt_toolkit\application\application.py", line 1002, in run
    return asyncio.run(coro)
           ~~~~~~~~~~~^^^^^^
  File "path\to\uv\python\cpython-3.13.2-windows-x86_64-none\Lib\asyncio\runners.py", line 191, in run
    raise RuntimeError(
        "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop

Example

import questionary
questionary.text("What's your first name").ask()

Steps to reproduce

Run test code as a mitmproxy plugin:

pip install mitmproxy
mitmweb -s test.py

Expected behaviour

Since Question.ask() is a synchronous API, it should not depend on or assume anything in the async world.

    def unsafe_ask(self, patch_stdout: bool = False) -> Any:

# ...
        if patch_stdout:
            with prompt_toolkit.patch_stdout.patch_stdout():
                return self.application.run(in_thread=True)
        else:
            return self.application.run(in_thread=True)

Latest version

  • I have checked that this issue occurs on the latest version of questionary.

Questionary version

questionary==2.1.0

Prompt Toolkit version

prompt-toolkit==3.0.50

Operating System

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions