简体   繁体   English

使用 tqdm 在进度条前打印消息

[英]Print message before progress bar using tqdm

In my python project I'm using tqdm module to display a progress bar.在我的 python 项目中,我使用tqdm模块来显示进度条。 I want to print a persistent message on the line before the progress bar.我想在进度条之前的行上打印一条持久消息。

The set_description method prints the message on the same line, whilte tqdm.write creates a new line. set_description方法在同一行打印消息,同时tqdm.write创建一个新行。

Using set_description使用set_description

$ python pbar.py {Task_1 message} 3%|████ ]

Is is possible to achieve this是否有可能实现这一目标

$ python pbar.py {Task_1 message} 3%|████ ]

Edit:编辑:

from tqdm import tqdm

pbar = tqdm(m_list)
for item in m_list:
   # Do work
   pbar.update(1)
pbar.close()

Simple example with a loop:带循环的简单示例:

import tqdm,time

for i in tqdm.tqdm(range(9),desc="{Task_1 message}"):
    time.sleep(0.1)

final output:最终输出:

{Task_1 message}: 100%|##############################################| 9/9 [00:00<00:00,  9.99it/s]

If you add \\n to the description, it will trash your output like this:如果您将\\n添加到描述中,它将像这样丢弃您的输出:

{Task_1 message}
{Task_1 message}                                            | 0/9 [00:00<?, ?it/s]
{Task_1 message}                                    | 1/9 [00:00<00:00,  9.99it/s]
{Task_1 message}#                                   | 2/9 [00:00<00:00,  9.99it/s]
{Task_1 message}######                              | 3/9 [00:00<00:00,  9.99it/s]
{Task_1 message}###########                         | 4/9 [00:00<00:00,  9.99it/s]
{Task_1 message}################                    | 5/9 [00:00<00:00,  9.99it/s]
{Task_1 message}#####################               | 6/9 [00:00<00:00,  9.96it/s]
{Task_1 message}##########################          | 7/9 [00:00<00:00,  9.97it/s]
{Task_1 message}###############################     | 8/9 [00:00<00:00,  9.98it/s]
: 100%|#############################################| 9/9 [00:00<00:00,  9.98it/s]

The only thing you can do is to print the description first, and run the task without description, as you can only delete the current line in the terminal.你唯一能做的就是先打印描述,然后在没有描述的情况下运行任务,因为你只能在终端中删除当前行。

import tqdm,time

print("{Task_1 message}")
for i in tqdm.tqdm(range(9)):
    time.sleep(0.1)

As previously said, you can only delete the current line in the terminal (using \\r ), there are numerous topics about that limitation on SO.如前所述,您只能删除终端中的当前行(使用\\r ),关于 SO 限制的主题有很多。

The alternative is using curses, but that's a completely different approach.另一种方法是使用curses,但这是一种完全不同的方法。

这是一个可能的解决方法,对我有用:

print("Your message", flush=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM