首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将python的“导入此”作为字符串返回?

如何将python的“导入此”作为字符串返回?
EN

Stack Overflow用户
提问于 2014-05-21 21:43:10
回答 5查看 3.5K关注 0票数 12

打字

代码语言:javascript
复制
import this 

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

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-05-21 21:54:58

您可以暂时将stdout重定向到StringIO实例import this,然后获取其值。

代码语言:javascript
复制
>>> 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。看起来是这样的:

代码语言:javascript
复制
>>> import contextlib, io
>>> zen = io.StringIO()
>>> with contextlib.redirect_stdout(zen):
...    import this
...
>>> print(zen.getvalue())

在Python3.8+中,也可以这样做:

代码语言:javascript
复制
>>> import contextlib, io
>>> with contextlib.redirect_stdout(zen := io.StringIO()):
...    import this
...
>>> print(zen.getvalue())
票数 12
EN

Stack Overflow用户

发布于 2014-05-21 21:54:22

让我们看看this.py做了什么:

代码语言:javascript
复制
s = "some encrypted string"
d = a map to decrypt the string

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

让我们注意,加密只是ROT13。

所以如果我们真的想抓住绳子,我们可以:

代码语言:javascript
复制
import this
s = this.s.decode('rot13')

或者,为了显式地遵循this.py模块的样式.

代码语言:javascript
复制
import this
s = "".join([this.d.get(c, c) for c in this.s])
票数 4
EN

Stack Overflow用户

发布于 2018-06-22 12:27:54

我认为接受的答案对于这种情况来说太复杂了(但是对于捕获一般的标准输出来说非常有趣)。

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

代码语言:javascript
复制
import this
import codecs

zen_of_python = codecs.encode(this.s, 'rot13')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23794344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档