打字
import this 将返回Python的禅,但我似乎无法找到关于的解决方案--如何将其设置为字符串变量,我可以在代码中进一步使用该变量.
发布于 2014-05-21 21:54:58
您可以暂时将stdout重定向到StringIO实例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!这段代码适用于python2.7 --对于python 3,使用io.StringIO而不是cStringIO.StringIO,并查看3.4中添加的contextlib.redirect_stdout。看起来是这样的:
>>> import contextlib, io
>>> zen = io.StringIO()
>>> with contextlib.redirect_stdout(zen):
... import this
...
>>> print(zen.getvalue())在Python3.8+中,也可以这样做:
>>> import contextlib, io
>>> with contextlib.redirect_stdout(zen := io.StringIO()):
... import this
...
>>> print(zen.getvalue())发布于 2014-05-21 21:54:22
让我们看看this.py做了什么:
s = "some encrypted string"
d = a map to decrypt the string
print "".join([d.get(c, c) for c in s])让我们注意,加密只是ROT13。
所以如果我们真的想抓住绳子,我们可以:
import this
s = this.s.decode('rot13')或者,为了显式地遵循this.py模块的样式.
import this
s = "".join([this.d.get(c, c) for c in this.s])发布于 2018-06-22 12:27:54
我认为接受的答案对于这种情况来说太复杂了(但是对于捕获一般的标准输出来说非常有趣)。
在Python 3中,只需执行以下操作,就可以将Python的禅作为字符串:
import this
import codecs
zen_of_python = codecs.encode(this.s, 'rot13')https://stackoverflow.com/questions/23794344
复制相似问题