如何使用 python 修复终端最后一行的进度条?

How to fix a progress bar at the terminal's last line using python?

为了对参数 space 进行大扫描以进行科学计算,这在我的计算机上需要花费几个小时,我想实现一个进度条(例如来自 tqdm 包)。在程序计算期间,我希望程序使用 print() 打印它在其搜索的网格上的确切位置和一些错误消息。使用 tqdm 中的标准代码会在每几行代码中产生一个条,但不会在终端的最后一行中产生一个进度条,这对我的应用程序是有好处的。

这是我的意思的最小版本:

from tqdm import tqdm
from time import sleep

for i in tqdm(range(10), position=0, leave=True):
    print("\nAfter this comment there will be a new progress bar.")
    sleep(0.5)

代码片段产生如下输出:

  0%|                                                    | 0/10 [00:00<?, ?it/s]
After this comment there will be a new progress bar.
 10%|████▍                                       | 1/10 [00:00<00:04,  2.00it/s]
After this comment there will be a new progress bar.
 20%|████████▊                                   | 2/10 [00:01<00:04,  2.00it/s]
After this comment there will be a new progress bar.
 30%|█████████████▏                              | 3/10 [00:01<00:03,  2.00it/s]
After this comment there will be a new progress bar.
 40%|█████████████████▌                          | 4/10 [00:02<00:03,  1.99it/s]
After this comment there will be a new progress bar.
 50%|██████████████████████                      | 5/10 [00:02<00:02,  1.99it/s]
After this comment there will be a new progress bar.
 60%|██████████████████████████▍                 | 6/10 [00:03<00:02,  1.99it/s]
After this comment there will be a new progress bar.
 70%|██████████████████████████████▊             | 7/10 [00:03<00:01,  1.99it/s]
After this comment there will be a new progress bar.
 80%|███████████████████████████████████▏        | 8/10 [00:04<00:01,  1.99it/s]
After this comment there will be a new progress bar.
 90%|███████████████████████████████████████▌    | 9/10 [00:04<00:00,  1.99it/s]
After this comment there will be a new progress bar.
100%|███████████████████████████████████████████| 10/10 [00:05<00:00,  1.99it/s]

您是否知道 tqdm 的替代方案,一个进度条的快速实现,该进度条保持在下方并且只是增长(连同 tqdm 提供的功能)或者我可能只需要给 tqdm 的正确论据?

谢谢!

听起来您正在寻找 tqdm 的 .write() 方法。

也就是说,如果您真的需要文本输出和进度条,我的解决方案是记录到一个文件。

请注意,使用默认值,您知道打印错误/输出的迭代次数,而无需通过 variable/exc_info 或类似方式提供。由于这个原因,我很少使用 tqdm.write()。

您可以使用 Rich,它允许您在显示进度条的同时进行打印。