鱼C论坛

 找回密码
 立即注册
查看: 1735|回复: 2

[已解决]求助,关于多线程print问题。。。

[复制链接]
发表于 2020-11-15 22:52:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 兰竹皋 于 2020-11-15 23:15 编辑


  1. from multiprocessing.pool import ThreadPool
  2. import time

  3. def progress_bar(total, ncols=10, desc='Processing', unit='it'):
  4.     def get_bar(l, n, ncol):
  5.         r = ncol - l - 1
  6.         bar = ''.join(['#' for i in range(l)])
  7.         if l != ncol:
  8.             bar += f'{n}'
  9.         bar += ''.join([' ' for i in range(r)])
  10.         return '|'+bar+'|'

  11.     processing = f'{0:>3d}%'
  12.     bar = get_bar(0, 0, ncols)
  13.     mod = f'{desc}:  {bar} {processing:>4s}'
  14.     print('\r'+mod, end='')

  15.     for i in range(total):
  16.         start_time = time.time()
  17.         # 内容处理
  18.         time.sleep(0.1)

  19.         stop_time = time.time()
  20.         delta_time = stop_time - start_time

  21.         temp = (i+1)/total
  22.         processing = f'{int(temp*100):>3d}%'
  23.         l = int(temp*ncols)
  24.         n = int(temp*ncols*10)%10
  25.         bar = get_bar(l, n, ncols)
  26.         mod = f'{desc}:  {bar} {processing:>4s}  {1/delta_time:.2f}it/s'
  27.         print('\r'+mod, end='')

  28.     print('\n', end='')


  29. def main():
  30.     print('main start')
  31.     pool = ThreadPool(5)
  32.     for i in range(5):
  33.         pool.apply_async(progress_bar, (100,50))
  34.         time.sleep(1)
  35.     pool.close()
  36.     pool.join()
  37.     print('main over')

  38. main()
复制代码

读者好,代码如上,我想写个简单的类似tqdm的进度条展示程序。
但在多线程中,每个线程print的每一行都重复在一行中,如图(可能看不出来,但这一行中包括了5个线程):
1.png
请问,如何可以让他们分开来分别覆盖输出?类似:
2.png
最佳答案
2020-11-16 00:40:03
光靠多线程多进程并不能实现多行异步刷新,要实现多行异步刷新,在windows上可能需要curses库,或者调用windows API。linux上同样可以使用curses库,或者借助终端控制码。
至于有没有现成的库可以帮助实现就不知道了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-11-16 00:40:03 From FishC Mobile | 显示全部楼层    本楼为最佳答案   
光靠多线程多进程并不能实现多行异步刷新,要实现多行异步刷新,在windows上可能需要curses库,或者调用windows API。linux上同样可以使用curses库,或者借助终端控制码。
至于有没有现成的库可以帮助实现就不知道了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-11-16 11:14:48 | 显示全部楼层
hrp 发表于 2020-11-16 00:40
光靠多线程多进程并不能实现多行异步刷新,要实现多行异步刷新,在windows上可能需要curses库,或者调用win ...

谢谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-26 18:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表