【问题标题】:How can I encode all text that a Python program outputs?如何编码 Python 程序输出的所有文本?
【发布时间】:2013-02-22 18:29:59
【问题描述】:

我的朋友正在尝试编写一个程序,他希望它能够根据 int 变量设置为 01 在输出普通文本和使用 Rot13 编码的文本之间切换。我们已经使用"text".encode('rot13') 进行了测试,它可以对文本进行编码,但是必须有一种更简单的方法来使程序输出的任何内容都使用 rot13 进行编码,而不是使用if 0, output text, if 1, output rot13 text 包装文本输出的每个实例。

我希望有某种编码,我可以将所有代码都包裹起来以使其工作,但我尝试在线搜索并找不到任何东西。对此的任何帮助将不胜感激。

【问题讨论】:

  • 你试过猴子补丁stdout吗?
  • 文本是如何输出的?与print?

标签: python encode final translate output


【解决方案1】:

您可以像这样重定向输出:

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! 输出。

【讨论】:

    【解决方案2】:

    我强烈建议不要猴子修补sys.stdoutsys.stderr,这是一种不好的做法,因为它可能会破坏您正在使用的其他模块或使用您的代码的其他模块。 p>

    更安全的方法是使用logging 模块的StreamHandlercodecs module's encoded writer 将编码消息打印到默认的stdoutstderr 处理程序:

    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(...)获得有意义的调试消息

    【讨论】:

      【解决方案3】:

      只需覆盖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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 2012-12-28
        • 2021-03-23
        • 2017-02-19
        • 2020-11-03
        • 1970-01-01
        相关资源
        最近更新 更多