将Python Progress Bar安装到所有命令提示符窗口大小中

发布于 2025-01-27 09:25:18 字数 292 浏览 3 评论 0 原文

在调整CMD窗口尺寸时,如何在所有命令提示符窗口大小上使进度栏大小在所有命令提示窗口大小上相同,而不会分为一半甚至多次?

def进度栏(流,块,字节剩余):

percent = 100 * (float (bytes remaining) / stream file size)
bar = '█' * int(percent) + '-' * int((100 - percent))
print(f"\r Downloading:  |{bar}|{percent:.2f}%", end="\r")

How to make the progress bar size same on same line at all command prompt window sizes without splitting into half or even multiple times when adjusting the cmd window size?

def progress bar(stream, chunk, bytes remaining):

percent = 100 * (float (bytes remaining) / stream file size)
bar = '█' * int(percent) + '-' * int((100 - percent))
print(f"\r Downloading:  |{bar}|{percent:.2f}%", end="\r")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玻璃人 2025-02-03 09:25:18
  1. 确定末端宽度
    您可以使用 os.get_terninal_size(
width = os.get_terminal_size().columns
  1. )您的其余文本
  2. 使用您的百分比作为比率来计算多少条字符(█)和填充字符( - )用于填充其余部分。
   remainder = width - len_text
   bar_chars = int(percent/100) * remainder
   fill_chars = remainder - bar_chars
   bar = '█' * bar_chars + '-' * fill_chars

如果您可以在窗口大小上放在窗口大小上,直到重新绘制为止,那么您就完成了。如果您希望它立即重新绘制,则需要添加一个信号处理程序,以

如今,您可以只使用一个库,例如 emlighten 包括其他功能,例如颜色和多个进度条。

import enlighten

manager = enlighten.get_manager()
pbar = manager.counter(total=file_size, desc='Downloading', unit='bytes')

# This part will vary based on your implementation, but here is an example
while len(data) < file_size:
   chunk = get_next_chunk()
   data += chunk
   pbar.update(len(chunk))

有一个示例 ftp downloader 在repo中。

  1. Determine Terminal width
    You can use os.get_terminal_size() to do that
width = os.get_terminal_size().columns
  1. Determine the size of the rest of your text
  2. Use your percentages as a ratio to calculate how much bar character(█) and fill character(-) to use to fill the remainder.
   remainder = width - len_text
   bar_chars = int(percent/100) * remainder
   fill_chars = remainder - bar_chars
   bar = '█' * bar_chars + '-' * fill_chars

If you are ok with it being off on a window resize until it's redrawn, then you're done. If you want it to redraw immediately, you need to add a signal handler for signal.SIGWINCH.

Now all that being said, you could just use a library like Enlighten that already handles all of this and includes other features like color and multiple progress bars.

import enlighten

manager = enlighten.get_manager()
pbar = manager.counter(total=file_size, desc='Downloading', unit='bytes')

# This part will vary based on your implementation, but here is an example
while len(data) < file_size:
   chunk = get_next_chunk()
   data += chunk
   pbar.update(len(chunk))

There's an example ftp downloader in the repo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文