如何在jupyter-notebook中实现进度条?
我已经这样做了:
count = 0
max_count = 100
bar_width = 40
while count <= max_count:
time.sleep(.1)
b = bar_width * count / max_count
l = bar_width - b
print '\r' + u"\u2588" * b + '-' * l,
count += 1
当我可以访问用于打印输出的循环时,这很棒。但有人知道有什么聪明的东西可以异步运行某种进度条吗?
答案 0 :(得分:21)
看看这个开源小部件:log-process
答案 1 :(得分:21)
这是一个解决方案(this之后)。
from ipywidgets import IntProgress
from IPython.display import display
import time
max_count = 100
f = IntProgress(min=0, max=max_count) # instantiate the bar
display(f) # display the bar
count = 0
while count <= max_count:
f.value += 1 # signal to increment the progress bar
time.sleep(.1)
count += 1
如果循环中更改的值为float
而不是int
,则可以改为使用ipwidgets.FloatProgress
。
答案 2 :(得分:14)
您可以尝试tqdm。示例代码:
# pip install tqdm
from tqdm import tqdm_notebook
# works on any iterable, including cursors.
# for iterables with len(), no need to specify 'total'.
for rec in tqdm_notebook(items,
total=total,
desc="Processing records"):
# any code processing the elements in the iterable
len(rec.keys())
答案 3 :(得分:1)
2020年8月,log-process小部件已不再集成到tqdm中,因此不再是一种适用的方法。第一个教程示例(使用新的API)在VSCode中是开箱即用的,我怀疑它在Jupyter中也能很好地工作。
from tqdm import tqdm
for i in tqdm(range(10)):
pass
答案 4 :(得分:0)
我已经使用ipywidgets和线程在方法调用期间实现了进度条,请参见下面的示例
import threading
import time
import ipywidgets as widgets
def method_I_want_progress_bar_for():
progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0)
finished = False
def work(progress):#method local to this method
total = 200
for i in range(total):
if finished != True:
time.sleep(0.2)
progress.value = float(i+1)/total
else:
progress.value = 200
break
thread = threading.Thread(target=work, args=(progress,))
display(progress)
#start the progress bar thread
thread.start()
#Whatever code you want to run async
finished = True #To set the process bar to 100% and exit the thread
答案 5 :(得分:0)
另一个使用 tqdm 的进度条示例
from tqdm import tqdm
my_list = list(range(100))
with tqdm(total=len(my_list)) as pbar:
for x in my_list:
pbar.update(1)