python3与python2字符串兼容_兼容Python 2和3的字符串文件编写器

我创建了一个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__()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值