-1

I'm trying to create a function that returns a 'pulse' every time it does something. The function must be passed as a callback if the person desires to receive the pulse. I'd like to print the pulses as new . character in the same line, so I did this:

import time

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

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

do_something(prtn)

but the code gets stuck and won't print anything!

  • 1
    you'll probably need to flush the output stream to see the output.. – thebjorn Feb 28 '17 at 23:08
  • @thebjorn yes, it worked. But why? –  Feb 28 '17 at 23:10
  • @GuerlandoOCs http://stackoverflow.com/a/10019605/1810460 – Hamms Feb 28 '17 at 23:11
  • @Hamms but why it isn't needed for print() but yes for print(something, end='') –  Feb 28 '17 at 23:13
  • @Hamms link explains the how, the reason it is done, as for most caching, is for performance. Stdout is line-cached, which is why you might not need a flush when using regular print (this can be os-dependent however). – thebjorn Feb 28 '17 at 23:14
  • Isn't `do` a reserved keyword that can't be used as an identifier? – Wombatz Mar 01 '17 at 00:26

2 Answers2

1

print is line buffered by default, and you are using print to print a value not terminated by a new line. So you will need to flush the buffer as a result in order to force it to output the value. See some ways of how to do this.

Community
  • 1
  • 1
Penguin Brian
  • 1,991
  • 14
  • 25
-1

You call a function like a parameter...

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)
  • 1. This does not solve OP's problem and 2. you missed the point: OP **wants** to pass a function as a parameter. – Wombatz Mar 01 '17 at 00:25