给定一个函数
我需要使用线程或多进程来实现这样的操作吗?
类似于:
f
,如何为其编写实时进度条以显示执行进度呢?请注意,我无法更改 f
(它是来自另一个库的函数),因此无法在 f
中插入 pbar.update
调用(因此这是一篇有关非循环函数进度条的文章)。其他SO帖子已经解决了可以更改 f
的情况下的问题,但是当我无法访问 f
的内容时,我找不到或想到解决方案。我需要使用线程或多进程来实现这样的操作吗?
类似于:
@progress_bar
def func_wrapper(*args, **kwargs):
return f(*args, **kwargs)
或者:
start_progress_bar()
f()
需要帮助,感激不尽!
更新:我已经采用了@Acorn答案中提供的代码并以装饰器形式重写。
import concurrent.futures
import functools
import time
from tqdm import tqdm
def progress_bar(expected_time, increments=10):
def _progress_bar(func):
def timed_progress_bar(future, expected_time, increments=10):
"""
Display progress bar for expected_time seconds.
Complete early if future completes.
Wait for future if it doesn't complete in expected_time.
"""
interval = expected_time / increments
with tqdm(total=increments) as pbar:
for i in range(increments - 1):
if future.done():
# finish the progress bar
# not sure if there's a cleaner way to do this?
pbar.update(increments - i)
return
else:
time.sleep(interval)
pbar.update()
# if the future still hasn't completed, wait for it.
future.result()
pbar.update()
@functools.wraps(func)
def _func(*args, **kwargs):
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(func, *args, **kwargs)
timed_progress_bar(future, expected_time, increments)
return future.result()
return _func
return _progress_bar
if __name__ == "__main__":
@progress_bar(expected_time=11)
def test_func():
time.sleep(10)
return "result"
print(test_func()) # prints "result"
f
时更新,还是在f
内部的每次loop
发生时更新?前者可以通过你所提到的“类似于某物”的注释实现,而后者则需要f
支持一个回调函数或者像你提到的那样,能够访问f
的内容。 - Geoffrey Garrett