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

时间:2014-05-21 21:43:11

标签: python

打字

import this 

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

5 个答案:

答案 0 :(得分:6)

您可以暂时将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())

答案 1 :(得分:3)

让我们看看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])

答案 2 :(得分:1)

在这种情况下,我认为可接受的答案过于复杂(尽管对于捕获标准输出而言非常有趣)。

在Python 3中,只需执行以下操作,就可以将 Python禅作为字符串获取:

using

答案 3 :(得分:0)

字符串存储在this.s中,但是 这很有趣,因为它已经加密了:

>>> help(this)
NAME
    this

FILE
    /usr/lib/python2.7/this.py

MODULE DOCS
    http://docs.python.org/library/this

DATA
    c = '!'
    d = {'A': 'N', 'B': 'O', 'C': 'P', 'D': 'Q', 'E': 'R', 'F': 'S', 'G': ...
    i = 25
    s = "Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf o...bar ubaxvat ...

$ head /usr/lib/python2.7/this.py
s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.

答案 4 :(得分:0)

我是在Pycharm(IDE)中做到的,如下所示:

import this
print()