【发布时间】:2018-12-21 06:04:40
【问题描述】:
我正在尝试在进度条下方为长时间运行的函数实现一个简单的微调器(使用改编自 this answer 的代码)。
[######## ] x%
/ Compressing filename
我在脚本的主线程中运行压缩和进度条,而在另一个线程中运行微调器,因此它实际上可以在压缩发生时旋转。但是,我对进度条和微调器都使用curses,并且都使用curses.refresh()
有时终端会随机输出乱码,我不知道为什么。我认为这是由于微调器的多线程特性,当我禁用微调器时,问题就消失了。
这是微调器的伪代码:
def start(self):
self.busy = True
global stdscr
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
threading.Thread(target=self.spinner_task).start()
def spinner_task(self):
while self.busy:
stdscr.addstr(1, 0, next(self.spinner_generator))
time.sleep(self.delay)
stdscr.refresh()
这是进度条的伪代码:
progress_bar = "\r[{}] {:.0f}%".format("#" * block + " " * (bar_length - block), round(progress * 100, 0))
progress_file = " {} {}".format(s, filename)
stdscr.clrtoeol()
stdscr.addstr(1, 1, " ")
stdscr.clrtoeol()
stdscr.addstr(0, 0, progress_bar)
stdscr.addstr(1, 1, progress_file)
stdscr.refresh()
并从main() 调用,例如:
spinner.start()
for each file:
update_progress_bar
compress(file)
spinner.stop()
为什么输出有时会损坏?是因为单独的线程吗?如果是这样,有什么更好的设计方法建议吗?
【问题讨论】:
-
您的应用程序的其余部分是否使用诅咒?还是您只是将它用于这一功能?
-
curses仅用于操作终端输出。应用程序的其余部分使用 Python 和其他模块
标签: python multithreading curses