tags:

views:

44

answers:

3

from the interactive prompt:

>>> import sys
>>> sys.stdout.write('is the')
is the6

what is '6' doing there?

another example:

>>> for i in range(3):
...     sys.stderr.write('new black')
... 
9
9
9
new blacknew blacknew black

where are the numbers coming from?

+2  A: 

In 3.x the write method of a file object returns the number of bytes written, and the interactive prompt prints out the return value of whatever you are running. So you print out 'is the' (6 bytes), and the interpreter then prints out 6 (the return from write). See the relevant docs for 3.1.

This does not happen before 3.0 as the write method returned None, and therefore nothing was printed.

Mike Boers
don't take it back. the behavior is the same on my machine using python 3.1.2. and the `write()` of file object in python 3.x do return the number of bytes written... if the OP assign the return value of the write to a dummy variable, the spurious output will disappear.
Adrien Plisson
@Adrien: Thanks for pointing that out! I have corrected myself.
Mike Boers
A: 
cthom06
A: 

This happens on Python3, but not Python2.

Mike is correct that the write in Python3 is returning the number of bytes written, which is then being printed by the interactive shell.

the write in Python2 returned None, so nothing was printed

gnibbler