Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python `print` passing extra text to sys.stdout?

This is probably something stupid I am missing but it has really got me hung up on a larger project (c extension) that I am writing.

Why is print "Hello, World!" passing None and an extra \n to sys.stdout here?

>>> import sys
>>> class StdOutHook:
...     def write(self, text):
...         sys.__stdout__.write("stdout hook received text: %s\n" % repr(text))
... 
>>> class StdErrHook:
...     def write(self, text):
...         sys.__stderr__.write("stderr hook received text: %s\n" % repr(text))
... 
>>> sys.stdout = StdOutHook()
>>> sys.stderr = StdErrHook()
>>> 
>>> def x():
...     print "Hello, World!"
... 
>>> 
>>> print x()
stdout hook received text: 'Hello, World!'
stdout hook received text: '\n'
stdout hook received text: 'None'
stdout hook received text: '\n'
>>> 
like image 541
chown Avatar asked Nov 27 '11 20:11

chown


1 Answers

print x() prints the return value of x() which is implicitly None

Either replace print "Hello world" with return "Hello world" or replace print x() with x()

like image 83
ThiefMaster Avatar answered Nov 12 '22 23:11

ThiefMaster