|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 兰竹皋 于 2020-11-16 11:33 编辑
读者好,这个很奇怪的问题,如下代码,可以正常运行:from multiprocessing.pool import ThreadPool
import time
def progress_bar(total, ncols=10, desc='Processing', unit='it'):
def get_bar(l, n, ncol):
r = ncol - l - 1
bar = ''.join(['#' for i in range(l)])
if l != ncol:
bar += f'{n}'
bar += ''.join([' ' for i in range(r)])
return '|'+bar+'|'
processing = f'{0:>3d}%'
bar = get_bar(0, 0, ncols)
mod = f'{desc}: {bar} {processing:>4s}'
print('\r'+mod, end='')
for i in range(total):
start_time = time.time()
# 内容处理
time.sleep(0.1)
stop_time = time.time()
delta_time = stop_time - start_time
temp = (i+1)/total
processing = f'{int(temp*100):>3d}%'
l = int(temp*ncols)
n = int(temp*ncols*10)%10
bar = get_bar(l, n, ncols)
mod = f'{desc}: {bar} {processing:>4s} {1/delta_time:.2f}it/s'
print('\r'+mod, end='')
print('\n', end='')
def main():
print('main start')
pool = ThreadPool(5)
for i in range(5):
pool.apply_async(progress_bar, (100,50))
time.sleep(1)
pool.close()
pool.join()
print('main over')
main()
结果:
但在改了progress函数最下方mod字符串后,就不能运行了。。。。为什么?没有报错,就是循环没有运行。。。from multiprocessing.pool import ThreadPool
import time
def progress_bar(total, ncols=10, desc='Processing', unit='it'):
def get_bar(l, n, ncol):
r = ncol - l - 1
bar = ''.join(['#' for i in range(l)])
if l != ncol:
bar += f'{n}'
bar += ''.join([' ' for i in range(r)])
return '|'+bar+'|'
processing = f'{0:>3d}%'
bar = get_bar(0, 0, ncols)
mod = f'{desc}: {bar} {processing:>4s}'
print('\r'+mod, end='')
start_time = time.time()
for i in range(total):
sub_start_time = time.time()
# 内容处理
time.sleep(0.1)
sub_stop_time = time.time()
sub_delta_time = sub_stop_time - sub_start_time
delta_time = sub_stop_time - start_time
remain_time = (total - i - 1)*sub_delta_time
temp = (i+1)/total
processing = f'{int(temp*100):>3d}%'
l = int(temp*ncols)
n = int(temp*ncols*10)%10
bar = get_bar(l, n, ncols)
mod = f'{desc}: {bar} {processing:>4s} [{delta_time//60:0>2d}:{delta_time%60:0>2d}<{remain_time//60:0>2d}:{remain_time%60:0>2d}, {1/sub_delta_time:.2f}it/s]'
print('\r'+mod, end='')
print('\n', end='')
def main():
print('main start')
pool = ThreadPool(5)
for i in range(5):
pool.apply_async(progress_bar, (100,50))
time.sleep(1)
pool.close()
pool.join()
print('main over')
main()
结果:
希望得到解惑,谢谢。。。
本帖最后由 gonff 于 2020-11-18 19:06 编辑
试了一下,主要原因有两个:
其一是remain_time和sub_delta_time都没有定义;(如果你其他语句里定义了,那就没这个问题)
其二是d不支持浮点型。例如
>>> f'{0.1:>2d}'
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
f'{0.1:>2d}'
ValueError: Unknown format code 'd' for object of type 'float'
>>> f'{0.1:>.2f}'
'0.10'
这两个错误导致,for i in range(total)内语句每次执行到mod这里就跳出。不会显示。最终显示的只有初始化用的那个进度条。
我改成了这样:
mod = f'{desc}: {bar} {processing:>4s} [{delta_time//60:.2f}<{delta_time%60:>.2f}{1/delta_time:.2f}it/s]'
可以显示。你可以再改一下变成你需要的。
另外如果你要求整数的话就int作用一下
{int(delta_time//60):>2d}
|
|