我的朋友正在尝试编写一个程序,他希望它能够根据int变量是设置为0还是1来在输出普通文本和使用Rot13编码的文本之间切换。我们已经使用"text".encode('rot13')进行了测试,它可以对文本进行编码,但是必须有一种比用if 0, output text, if 1, output rot13 text包装每个文本输出实例更简单的方法来使程序输出的任何内容都用rot13编码。
我希望有某种编码,我可以包装所有的代码,使其工作,但我尝试在网上搜索,没有找到任何东西。在这方面的任何帮助都将非常感谢。
发布于 2013-02-23 02:49:26
您可以重定向输出,如下所示:
import sys
old_stdout = sys.stdout
class MyOut(object):
def write(self, string):
# Do what ever you want with the string
old_stdout.write(string.upper())
def flush(self):
pass
sys.stdout = MyOut()
print "Hello world!"上面的脚本将为您提供HELLO WORLD!输出。
发布于 2013-02-23 03:46:19
我强烈建议不要为sys.stdout sys.stderr,或打补丁这是一种糟糕的做法,因为它可能会破坏你正在使用的其他模块,或者使用你代码的其他模块。
一种更安全的方法是将logging模块的StreamHandler与codecs module's encoded writer结合使用,以将编码的消息打印到默认的stdout或stderr处理程序:
import logging
# import codecs # not necessary, this is embedded in logging
# import sys # not necessary, this is embedded in logging
# get your encoding flag here...
flag = 1
# Log everything, and send it to stderr.
# create an encoded streamhandler with encoding based on flag
if flag == 1:
writer = logging.codecs.getwriter('rot13')(logging.sys.stderr)
streamhandler = logging.StreamHandler(stream = writer)
else:
streamhandler = logging.StreamHandler() # defaults to unencoded stderr
# you can use sys.stdout instead,
# it depends on preference and use case
# set the log level threshold
streamhandler.setLevel(logging.DEBUG)
# create a basic logger
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(streamhandler)
# now, instead of print, use log.debug(message)
print 'hello world'
log.debug('hello world')使用日志记录模块的优点是,它还允许您设置自己的自定义格式化程序和过滤器,以及使用log.exception(...)获取有意义的调试消息
发布于 2013-02-23 02:56:12
只需覆盖sys.stdout即可。
import sys
# Save the original stdout
original = sys.stdout
# Create our own stdout
class writer(object) :
def write(self, text):
# Do encoding here
#text = rot13encode(text)
original.write(text)
# Override stdout with our stdout
sys.stdout = writer()
# print as usual
print "Hello"https://stackoverflow.com/questions/15030821
复制相似问题