prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.11k stars 717 forks source link

Progress dialog (also progress dialog example) not working #1740

Open emanuelep57 opened 1 year ago

emanuelep57 commented 1 year ago

The example code of progress_dialog.py is not working.

Actually, I think the issue is with the progress dialog itself:

lib/python3.10/site-packages/prompt_toolkit/shortcuts/dialogs.py", line 267, in progress_dialog loop = get_running_loop() RuntimeError: no running event loop

menteora commented 9 months ago

This code work for me. I hope this will help you.

prompt-toolkit==3.0.39

#!/usr/bin/env python
"""
Example of a progress bar dialog.
"""
import os
import time
import asyncio
from prompt_toolkit.shortcuts import progress_dialog

def worker(set_percentage, log_text):
    """
    This worker function is called by `progress_dialog`. It will run in a
    background thread.

    The `set_percentage` function can be used to update the progress bar, while
    the `log_text` function can be used to log text in the logging window.
    """
    percentage = 0
    for dirpath, dirnames, filenames in os.walk("../.."):
        for f in filenames:
            log_text(f"{dirpath} / {f}\n")
            set_percentage(percentage + 1)
            percentage += 2
            time.sleep(0.1)

            if percentage == 100:
                break
        if percentage == 100:
            break

    # Show 100% for a second, before quitting.
    set_percentage(100)
    time.sleep(1)

async def main():
    await progress_dialog(
        title="Progress dialog example",
        text="As an examples, we walk through the filesystem and print "
        "all directories",
        run_callback=worker,
    ).run_async()

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())
    # ALSO WORK asyncio.run(main())