2017-02-28 61 views
-1

我试图创建一个函数,每次执行某个操作时都返回一个“脉冲”。如果该人希望接收脉冲,则该函数必须作为回调传递。我想打印的脉冲,在同一行新.性格,所以我这样做:用函数回调在python3中打印同一行

import time 

def do_something(do=None): 
    while True: 
     time.sleep(1) 
     if do: do('.') 

def prtn(text): 
    print(text, end=' ') 

do_something(prtn) 

但代码卡并不会打印出任何东西!

+1

你可能需要刷新输出流才能看到输出。 – thebjorn

+0

@thebjorn是的,它的工作。但为什么? –

+0

@GuerlandoOCs http://stackoverflow.com/a/10019605/1810460 – Hamms

回答

2

print是默认缓冲线,并且正在使用print打印不是由新行终止的值。所以你将需要刷新缓冲区,以强制它输出值。看到how to do this的一些方法。

-1

你叫象参数的函数...

import time 

def prtn(text): 
    print(text, end=' ') 

def do_something(do=False): 
    while True: 
     time.sleep(1) 
     if prtn: prtn('.') 

do_something(do=True) 
+0

1.这并不解决OP的问题,2.您错过了这一点:OP **希望**将函数作为参数传递。 – Wombatz