一个多进程程序,主进程阻塞,子进程不断打印等待效果直到主进程结束,原理是\x08
在ascii中表示退格键,理解为打印完后立马删掉打印下一个内容。
import sys, time
import multiprocessing DELAY = 0.1
DISPLAY = [ '|', '/', '-', '\\' ] def spinner_func(before='', after=''): write, flush = sys.stdout.write, sys.stdout.flush pos = -1 while True: pos = (pos + 1) % len(DISPLAY) msg = before + DISPLAY[pos] + after write(msg) flush() write('\x08' * len(msg)) time.sleep(DELAY) def long_computation(): time.sleep(5) def run(): spinner = multiprocessing.Process( None, spinner_func, args=('Please wait ... ', '')) spinner.start() try: long_computation() print('Computation done') finally: spinner.terminate()if __name__ == "__main__":run()
问题:
pycharm中看不见效果,在powershell或者cmd中可以看到效果。
解决:
pycharm设置Emulate terminal in output console