Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - 如何在Python中打印到stderr?(How to print to stderr in Python?)

There are several ways to write to stderr:

(有几种写stderr的方法:)

# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"

sys.stderr.write("spam
")

os.write(2, b"spam
")

from __future__ import print_function
print("spam", file=sys.stderr)

That seems to contradict zen of Python #13 ? , so what's the difference here and are there any advantages or disadvantages to one way or the other?

(这似乎与zen的Python#13 ?相矛盾,所以这里有什么区别,一种方式或另一种方式有什么优点或缺点?)

Which way should be used?

(应该使用哪种方式?)

? There should be one — and preferably only one — obvious way to do it.

(? 应该有一种-最好只有一种-显而易见的方法。)

  ask by wim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found this to be the only one short + flexible + portable + readable:

(我发现这是唯一的简短+灵活+便携式+可读的格式:)

from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

The function eprint can be used in the same way as the standard print function:

(可以使用与标准print功能相同的方式使用eprint功能:)

>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...