如何将python的"import this"作为字符串返回?

Max*_*axQ 7 python

打字

import this 
Run Code Online (Sandbox Code Playgroud)

将返回PythonZen,但我似乎找不到有关如何将其设置为等于字符串变量的解决方案,我可以在我的代码中进一步使用...

Ism*_*awi 7

您可以暂时重定向stdoutStringIO实例,import this然后获取其值.

>>> import sys, cStringIO
>>> zen = cStringIO.StringIO()
>>> old_stdout = sys.stdout
>>> sys.stdout = zen
>>> import this
>>> sys.stdout = old_stdout
>>> print zen.getvalue()
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Run Code Online (Sandbox Code Playgroud)

这段代码适用于python2.7 - 对于python 3,使用io.StringIO而不是cStringIO.StringIO,并且还看看contextlib.redirect_stdout在3.4中添加了哪些.这看起来像这样:

>>> import contextlib, io
>>> zen = io.StringIO()
>>> with contextlib.redirect_stdout(zen):
...    import this
...
>>> print(zen.getvalue())
Run Code Online (Sandbox Code Playgroud)

  • 我绝对认为这是回答这个问题的最合适的方法。它可以推广到其他有打印输出的模块,并且可以抵抗对“this”模块的实现更改。其他答案虽然有效,但非常具体,我们不妨告诉OP自己复制文本并将其粘贴到字符串文字中,或者链接到[PEP 20](http:// Legacy.python.org/dev/peps/pep-0020/)等。如果OP试图了解它是如何工作的,那么他们真正想要的是:http://stackoverflow.com/questions/5855758 (2认同)