P3 weird sys.stdout.write()

Dave Angel davea at ieee.org
Mon Aug 24 10:52:16 EDT 2009


Jerzy Jalocha N wrote:
> I've stumbled upon the following in Python 3:
>
> Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>   
>>>> import sys
>>>> sys.stdout.write("")
>>>>         
> 0
>   
>>>> sys.stdout.write("something")
>>>>         
> something9
>   
>
> write() is appending the length of the string to it's output. That's
> not how it worked in 2.6.
>
> What's the reason for this? Is this intended? I couldn't find a bug
> report for this.
>
>   
(You probably should be using 3.1, but that's not your particular 
problem here.)

The write() function changed in 3.0, but not in the way you're 
describing.  It now (usually) has a return value, the count of the 
number of characters written.  See the 3.1 docs:

file.write(/str/)

    Write a string to the file. Due to buffering, the string may not
    actually show up in the file until the flush() or close() method is
    called.

    The meaning of the return value is not defined for every file-like
    object. Some (mostly low-level) file-like objects may return the
    number of bytes actually written, others return None.

But because you're running from the interpreter, you're seeing the 
return value(9), which is suppressed if it's None, which it was in 
2.x.   This has nothing to do with how the language behaves in normal use.

DaveA




More information about the Python-list mailing list