Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My issue is that I have a function call it function1 which runs indefinitely. The function itself echo's "hello" every 1 second. Using the command:

function1 >> temp.txt

Every 1 second if I am to view the file temp.txt I should see a new line with "hello". However what's happening is that the function doesn't write to the file until its finished running. Therefore if I am to kill the function nothing will be written. Does anyone know of something I can do in this situation that will basically dynamically update temp.txt?

I have a python script set up the following way:

while [1>0]: print "hello" time.sleep(1)

Therefore this will always be running. Now I call this in a bash script

python >> temp.txt

If I kill the process no data is logged.

share|improve this question
I wonder that it works that way -- but the easiest thing to come up with would be turning your function into a separate shell script to be called instead. Would that be an acceptable solution? – Izzy Jul 20 '12 at 19:55
It would be extremely difficult to do this. Looking for a simpler solution – Matt Stokes Jul 20 '12 at 20:15
up vote 2 down vote accepted

Now that you mention it is not a shell function, but a python function in a python script: That explains some, and here comes your answer:

printing - How to flush output of Python print? - Stack Overflow

You need to put that inside your python function's loop: sys.stdout.flush() -- and of course you need to import sys before (or from sys import ... if you only need a part of it).

share|improve this answer
Works perfectly thank you! – Matt Stokes Jul 23 '12 at 14:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .