首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python需要一个类似字节的对象,而不是'str‘

Python需要一个类似字节的对象,而不是'str‘
EN

Stack Overflow用户
提问于 2019-03-05 04:16:40
回答 1查看 1.2K关注 0票数 0

我是Python的新手。我正在运行以下简单的web服务器:

代码语言:javascript
复制
from wsgiref.simple_server import make_server
from io import BytesIO

def message_wall_app(environ, start_response):
    output = BytesIO()
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/html; charset=utf-8')]
    start_response(status, headers)
    print(b"<h1>Message Wall</h1>",file=output)
##    if environ['REQUEST_METHOD'] == 'POST': 
##        size = int(environ['CONTENT_LENGTH'])
##        post_str = environ['wsgi.input'].read(size)
##        print(post_str,"<p>", file=output)
##    print('<form method="POST">User: <input type="text" '
##          'name="user">Message: <input type="text" '
##          'name="message"><input type="submit" value="Send"></form>', 
##           file=output)         
    # The returned object is going to be printed
    return [output.getvalue()]     

httpd = make_server('', 8000, message_wall_app)
print("Serving on port 8000...")

# Serve until process is killed
httpd.serve_forever()

不幸的是,我得到了以下错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\xxx\Python36\lib\wsgiref\handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "C:/xxx/Python/message_wall02.py", line 9, in message_wall_app
    print("<h1>Message Wall</h1>".encode('ascii'),file=output)
TypeError: a bytes-like object is required, not 'str'....

请指出我做错了什么。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-05 04:19:41

您不能使用print()来写入二进制文件。在写入文本文件对象之前,print()会将参数转换为str()

print() function documentation

将对象打印到文本流文件,以sep分隔,后跟end。..。

所有非关键字参数都会转换为字符串,就像 str() 一样,并写入到流中,以sep分隔,后跟end。

大胆强调我的观点。请注意,文件对象必须是文本流,而不是二进制流。

要么写入包装BytesIO()对象的TextIOWrapper() object,调用BytesIO()对象上的.write()直接写入bytes对象,要么写入StringIO() object并在末尾对结果字符串值进行编码。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54990897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档