python print function in real time

后端 未结 3 1870
粉色の甜心
粉色の甜心 2020-12-06 05:51

I recently switched OS and am using a newer Python (2.7). On my old system, I used to be able to print instantaneously. For instance, suppose I had a computationally intense

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 06:15

    Import the new print-as-function as in Python 3.x:

    from __future__ import print_function
    

    (put the statement at the top of your script/module)

    This allows you to replace the new print function with your own:

    def print(s, end='\n', file=sys.stdout):
        file.write(s + end)
        file.flush()
    

    The advantage is that this way your script will work just the same when you upgrade one day to Python 3.x.

    Ps1: I did not try it out, but the print-as-function might just flush by default.

    PS2: you might also be interested in my progressbar example.

提交回复
热议问题