How to flush output of print function?

后端 未结 13 1966
旧时难觅i
旧时难觅i 2020-11-21 05:15

How do I force Python\'s print function to output to the screen?

This is not a duplicate of Disable output buffering - the linked question is attempting unbuffe

13条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 05:33

    I first struggled to understand how the flush option was working. I wanted to do a 'loading display' and here is the solution I found:

    for i in range(100000):
        print('{:s}\r'.format(''), end='', flush=True)
        print('Loading index: {:d}/100000'.format(i+1), end='')
    

    The first line flushes the previous print and the second line prints a new updated message. I don't know if an one-line syntax exists here.

提交回复
热议问题