Python`print`将额外的文本传递给sys.stdout?

时间:2011-11-27 20:19:16

标签: python stdout stderr sys

这可能是我想念的愚蠢但是我真的把我挂在了一个更大的项目(c扩展名)上。

为什么print "Hello, World!"None\n传递给sys.stdout

>>> 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'
>>> 

3 个答案:

答案 0 :(得分:7)

print x()打印x()的返回值,隐含None

print "Hello world"替换为return "Hello world"或将print x()替换为x()

答案 1 :(得分:3)

两件事:

首先,除非另有说明,否则print会自动添加新行。如果您不想要新行添加逗号:

print "Hello, World!",

其次,您正在打印x()函数的返回值,该函数为None。函数f()等同于:

def x():
    print "Hello, World!"
    return None

因此print x()会打印None

答案 2 :(得分:1)

def x():
   print "Hello, World!"

将执行print并返回None - print生成了其他换行符,并且自您编写None后打印print x():)

如果您希望删除其他换行符,请将x改为:

def x():
   sys.stdout.write("Hello, World!")