ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

兼容Python 2和3的字符串文件编写器

2019-10-25 06:56:39  阅读:234  来源: 互联网

标签:python-unicode python-3-x python-2-7 stdout python


我创建了一个python Context Manager,它捕获所有输出sys.stdout(例如,使用print()),并将其写入文件.

问题是我无法同时使用python 2.7和3.6.

上下文管理器在内部使用

self.file_writer = open(self.log_file, 'w', encoding='utf8')

但是当我在Python 2.7中运行它时

print(u"a test string")

导致错误消息:

write() argument 1 must be unicode, not str

即使该字符串显然是unicode.

如果我将文件更改为

self.file_writer = open(self.log_file, 'wb')

那么它就可以在Python 2.7中工作,但在3.6中不行.

我需要怎么做才能使其适用于任何python版本?

以下是管理器的摘录:

PATH_PREFIX = "some/path/"
class manager:
    def __init__(self):
        self.log_file = os.path.join(PATH_PREFIX, 'log.txt')
    def __enter__(self):
        # create a file for logging
        self.log_file_stream = open(self.log_file, 'w', encoding='utf8')
        self.log_file_stream.__enter__()
        # redirect stdout to this file
        self.previous_stdout = sys.stdout
        sys.stdout = self.log_file_stream
        return self
    def __exit__(self, etype, value, exception_traceback):
        # stop redirecting stdout to the log file
        sys.stdout = self.previous_stdout
        # close the log file
        self.log_file_stream.__exit__()

解决方法:

sys.stdout在Python 2中应该是字节流,但在Python 3中是Unicode流.Python2的print在写入stdout之前将Unicode字符串编码为字节字符串,但是您已经覆盖了sys.stdout为Unicode.在Python 2和Python 3中都流式传输.

覆盖sys.stdout时,需要为Python 2提供一个字节流,但为Python 3提供一个Unicode流.可以使用sys.version_info.major来确定要支持的字节流.

标签:python-unicode,python-3-x,python-2-7,stdout,python
来源: https://codeday.me/bug/20191025/1926813.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有