gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:24:18 25 4
gpt4 key购买 nike

打字

import this 

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

最佳答案

您可以暂时重定向 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!

此代码适用于 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())

关于python - 如何将 python 的 "import this"作为字符串返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com