Python `print` 将额外的文本传递给 sys.stdout? [英] Python `print` passing extra text to sys.stdout?
本文介绍了Python `print` 将额外的文本传递给 sys.stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能是我遗漏的一些愚蠢的东西,但它确实让我挂断了我正在编写的一个更大的项目(c
扩展).
为什么 print "Hello, World!"
将 None
和一个额外的 \n
传递给 sys.stdout
> 在这里?
解决方案
print x()
打印 x()
的返回值,隐式 None
将 print "Hello world"
替换为 return "Hello world"
或将 print x()
替换为 x()
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'
>>>
解决方案
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()
这篇关于Python `print` 将额外的文本传递给 sys.stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文