简体   繁体   English

打印功能最近打印耗时的东西

[英]print function print lately on time consuming stuff

i am trying to understand, why start... is not print first. 我想了解,为什么要开始...不是先打印。 but got nothing... 但没有得到......

from __future__ import print_function
# from time import sleep

def sleeping():
    # sleep(2)
    for i in range(60000000):  # or xrange(60000000)
        pass

print('start...', end='')
sleeping()
print('stop.')

same thing happen in this 同样的事情发生在这

from __future__ import print_function
from time import sleep

print('this will print lately')

sleep(2)

print('and this one')

i have tried this on both python 3 and 2. on python 2 it works fine.but causes problem on python 3. 我已经在python 3和2上尝试了这个。在python 2上它运行正常。但是在python 3上引起问题。

EDIT : 编辑

different output on sublime text and terminal (may be configuration problem on sublime). sublime文本和终端上的不同输出(可能是sublime上的配置问题)。 on terminal, second one works well in both version and first one causes problem in both version. 在终端上,第二个在版本和第一个版本中运行良好导致两个版本中的问题。

sys.stdout (which print prints to by default) is line-buffered when running interactively. sys.stdout (默认情况下打印到print件)在交互式运行时是行缓冲的

Since print('start...', end='') makes the line not end, the output isn't automatically flushed out. 由于print('start...', end='')使得行不结束,因此输出不会自动刷新。

To force the buffer to be flushed, you can specify flush=True when calling print . 要强制刷新缓冲区,可以在调用print时指定flush=True

In your case: print('start...', end='', flush=True) 在你的情况下: print('start...', end='', flush=True)

Another option is to flush the stream manually by using sys.stdout.flush() . 另一种选择是使用sys.stdout.flush()手动刷新流。

Further reading: 进一步阅读:

The print statements are in most of the cases buffered. 在大多数情况下, print语句都是缓冲的。 In order to force print to stdout you have to flush the buffer (using sys): 为了强制打印到stdout,你必须刷新缓冲区(使用sys):

from __future__ import print_function
# from time import sleep
import sys


def sleeping():
    # sleep(2)
    for i in range(60000000):  # or xrange(60000000)
        pass

print('start...', end='')
sys.stdout.flush()
sleeping()
print('stop.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM