How can I return python's "import this" as a string?

You can temporarily redirect stdout to a StringIO instance, import this, and then get its value.

>>> 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!

This code works on python2.7 -- for python 3, use io.StringIO instead of cStringIO.StringIO, and also have a look at contextlib.redirect_stdout which was added in 3.4. That would look like this:

>>> import contextlib, io
>>> zen = io.StringIO()
>>> with contextlib.redirect_stdout(zen):
...    import this
...
>>> print(zen.getvalue())

Let's look at what this.py does:

s = "some encrypted string"
d = a map to decrypt the string

print "".join([d.get(c, c) for c in s])

Let's note that the encryption is just ROT13.

So if we really wanted to grab the string, we could do:

import this
s = this.s.decode('rot13')

Or, to explicitly follow the style of the this.py module...

import this
s = "".join([this.d.get(c, c) for c in this.s])

Tags:

Python