sys.stdout.write() question

  • Thread starter Gian Mario Tagliaretti
  • Start date
G

Gian Mario Tagliaretti

Hi all,

It is (I hope) a simple question,
I cannot figure out why sys.stdout.write() doesn't print immediatly the first
text in the small example below, but before it process the code in between
and then print both lines in one time.

#!/usr/bin/env python
import sys, time
sys.stdout.write('write ')
time.sleep(3)
sys.stdout.write('this\n')

if you try to run this, before it will wait 3 seconds and then print "write
this" in one time.

If I put \n here :

sys.stdout.write('write \n')

it work properly but I would like to print the text in one row.

thanks to all
Mario
 
I

Ivan Voras

Gian said:
#!/usr/bin/env python
import sys, time
sys.stdout.write('write ')
time.sleep(3)
sys.stdout.write('this\n')

if you try to run this, before it will wait 3 seconds and then print "write
this" in one time.

If I put \n here :

sys.stdout.write('write \n')

it work properly but I would like to print the text in one row.

It line-buffers the output. If you need to print something that is not 'a
whole line', use sys.stdout.flush() after the ...write()
 
R

Reinhold Birkenfeld

Gian said:
Hi all,

It is (I hope) a simple question,
I cannot figure out why sys.stdout.write() doesn't print immediatly the first
text in the small example below, but before it process the code in between
and then print both lines in one time.

#!/usr/bin/env python
import sys, time
sys.stdout.write('write ')
time.sleep(3)
sys.stdout.write('this\n')

if you try to run this, before it will wait 3 seconds and then print "write
this" in one time.

Apparently the stdout "file" is buffered on your system. Have a look at
file.flush() which could help you out.

Reinhold
 
P

Peter Hansen

Gian said:
It is (I hope) a simple question,
I cannot figure out why sys.stdout.write() doesn't print immediatly the first
text in the small example below, but before it process the code in between
and then print both lines in one time.

sys.stdout.flush(). Flush on a file object pushes out all the data
that has been buffered to that point.

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top