2016-12-01 23 views
1

我写了一个httpserver来为python2.7和python3.5提供html文件。python3将str转换为字节式的obj而不使用编码

def do_GET(self): 

    ... 
    #if resoure is api 
     data = json.dumps({'message':['thanks for your answer']}) 

    #if resource is file name 
     with open(resource, 'rb') as f: 
      data = f.read() 

    self.send_response(response) 
    self.send_header('Access-Control-Allow-Origin', '*') 
    self.end_headers() 
    self.wfile.write(data) # this line raise TypeError: a bytes-like object is required, not 'str' 

该代码在python2.7中工作,但在python 3中,它引发了上述错误。

我可以使用bytearray(data, 'utf-8')将str转换为字节,但html在web中更改。

enter image description here

我的问题: 怎么做才能支持python2和python3不使用2to3的工具和不改变文件的编码。

有没有更好的方式来读取文件,并在python2和python3中以相同的方式将内容发送到客户端?

在此先感谢。

回答

1

你只需要在二进制模式文本打开你的文件,而不是模式:

with open(resource,"rb") as f: 
    data = f.read() 

然后,data在Python 3 bytes对象,并在蟒蛇2 str,并它适用于两个版本。

作为一个积极的副作用,当此代码点击Windows框时,它仍然有效(否则像图像这样的二进制文件由于在文本模式下打开时进行了结束符终止转换而被破坏)。

+0

你的意思是在Python 3中。在这种情况下,仅在python中将返回值转换为'bytes(return_value,“ascii”)“。3.用'if if sys.version_info> =(3,):' –

+0

谢谢。:-)测试版本, –

相关问题