繁体   English   中英

是否可以将 tqdm 用于不是循环的进程?

[英]Is it possible to use tqdm for a process that isn't a loop?

我正在编写一个程序,其中一个操作需要几秒钟(加载一个大文件)。 幸运的是,它总是需要相同的时间。 所以,为用户着想,我想做一个进度条。 但是, tqdm似乎是为循环设计的。 假设sleep(10)是需要时间的过程。 我该如何解决这个问题?

我想为一个不是循环的漫长过程制作一个进度条。

from time import time, sleep
from tqdm import tqdm

for i in tqdm([1]):
    sleep(10)

这段代码的问题是进度条将保持为零,然后在过程结束时跳转到 100%。 我想要一个在 10 秒内持续变化的进度条。

您可以定义块大小。 持续 10 秒的条形假定您已经知道加载文件所需的时间...

尝试这个

from tqdm import tqdm_notebook as tqdm

chunk_size = 1000
total_chunks=nrows/chunk_size

chunks = pd.read_sql_query(query, connection, index_col='index_name',chunksize= chunk_size)
raw_train_data=pd.DataFrame()

with tqdm(total=total_chunks) as pbar:

    for chunk in chunks:
        raw_train_data = pd.concat([raw_train_data, chunk])
        pbar.update(1)

您可以使用线程加载文件,并循环遍历 tqdm(range(10)) 直到文件加载如下:

import logging
import threading
import time
from tqdm import tqdm


def thread_function(name):
    logging.info("Thread %s: starting", name)
    logging.info("Main    : file loading...")
    time.sleep(5)
    logging.info("Thread %s: finishing", name)


if __name__ == "__main__":
    logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO,
                        datefmt="%H:%M:%S")

    x = threading.Thread(target=thread_function, args=(1,))
    x.start()
    for i in tqdm(range(10)):
        if not x.is_alive():
            break
        time.sleep(1)
    x.join()
    logging.info("Main    : end.")
for _ in tqdm(range(10),desc="waiting..."):
    time.sleep(1)

手动设置 tqdm 的进度值:

#Manually set p_bar
p_bar = tqdm(range(10))
p_bar.update(5)
p_bar.refresh()
time.sleep(1)
#another way to do it
p_bar.n = 7
p_bar.refresh()

暂无
暂无

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

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