Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Typing

import this 

will return the Zen of Python, but nowhere do I seem to be able find a solution about how to set it equal to a string variable which I can use further on in my code...

like image 405
MaxQ Avatar asked May 21 '14 21:05

MaxQ


Video Answer


1 Answers

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())

In Python3.8+ you can also do:

>>> import contextlib, io
>>> with contextlib.redirect_stdout(zen := io.StringIO()):
...    import this
...
>>> print(zen.getvalue())
like image 166
Ismail Badawi Avatar answered Oct 18 '22 12:10

Ismail Badawi