While I was trying some stuffs in my Python 3 interpreter (Python 3.4.2, installed via brew), I encountered some weird outputs I didn\'t expected:
>>&g
You're right that it's the length. In Python 2, the File.write()
method returned None
. When the move was made to Python 3, the return value changed to be the number of characters written.
The reason you're getting the different output from stdout
and stderr
will probably have to do with the order in which things show up on the file handles.
For stdout
, write
outputs "foo"
then the REPL loop (in the grand tradition of PIN numbers and ATM machines) outputs the count to the same stream.
For stderr
, it's likely that the REPL loop outputs standard output first (the length) then the content of standard error.
Or, it may be totally non-deterministic, it's probably not something you should rely on, especially as the REPL loop doesn't really exist except in the interactive mode of the interpreter.
In the python interpreter, when you print something, it shows you the result on stdout and stderr.
I tested it out in my python 3.4. Here is what I think is happening
sys.std.write("foo") = > foo3
Interpreter writes "foo" to stdout. The interpreter then prints the result of the sys.stdout.write method, which is 3. The end result is foo3. Try sys.stdout.write("foo\n\n"). And this might help you see.
sys.stderr.write("bar") =>
3
bar
The err stream is not as fast as the stdout. The 3 result from the write shows up first with a new line character. The bar is printed after.
This behaviour is normal. This happens because sys.stdout.write()
returns the length of the text. Try this code again in a python file. you see, this doesn't happen anymore. This "weird stuff" happens because python automatically prints the return value unless you execute the code using a python file.
>>>'text'
'text'
if you do this in a python file, there will be no result. you can prevent this by stopping the return such as this:
>>>_=sys.stdout.write('text')
or doing this:
>>>def noreturn(value):
... pass
>>>noreturn(sys.stdout.write('text'))