gpt4 book ai didi

Python CLI 进度条/旋转器,无需迭代

转载 作者:行者123 更新时间:2023-11-30 22:34:24 25 4
gpt4 key购买 nike

关于 Python 脚本执行时终端中进度条的显示,存在许多现有问题,但每个问题都基于执行操作然后更新进度图形的循环。

不幸的是,我想要显示其进度的函数(或者至少是一个旋转器对象来显示它正在工作)是一个我无法(至少真的、真的不应该)改变的黑匣子。本质上,我想做的是:

#pseudocode input
print('Loading')
spinner.begin()
blackbox() #a few thousand operations happen in here
spinner.end()
print('Finished')

#pseudocode output
Loading.
Loading..
Loading...
Loading.
Loading..
Loading...
Finished

尽管理想情况下,这将是省略号的动画,而不是打印多行。在我开始构建愚蠢的 ASCII 动画之前,有一个主要障碍:

有没有办法同时运行spinnerblackbox()?或者,是否有一种方法可以每隔几百毫秒暂停 blackbox()(无论其内容如何),更新旋转器图形,然后从中断处恢复?

我已经用 progress 尝试过此操作模块,但运气不好...我什至无法让示例代码工作,它只是在我开始迭代后挂起,直到我按 Ctrl+C 退出。

最佳答案

我喜欢使用alive_progress为此。

alive_bar spinner

from typing import ContextManager, Optional
from alive_progress import alive_bar

def spinner(title: Optional[str] = None) -> ContextManager:
"""
Context manager to display a spinner while a long-running process is running.

Usage:
with spinner("Fetching data..."):
fetch_data()

Args:
title: The title of the spinner. If None, no title will be displayed.
"""
return alive_bar(monitor=None, stats=None, title=title)

安装:pip install alive-progress

关于Python CLI 进度条/旋转器,无需迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com