如何在一行中的套接字连接的send方法中将字符串编码为字节?

joh*_*nny 3 python sockets python-3.5

在Python 3.5中,使用套接字,我有:

message = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n'
s.send(message.encode())
Run Code Online (Sandbox Code Playgroud)

我怎么能在一行中做到这一点?我问,因为我有:

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
Run Code Online (Sandbox Code Playgroud)

但是在Python中需要3.5个字节,而不是字符串,所以这给出了错误:

builtins.TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

我不应该使用发送吗?

Ben*_*son 6

str的类型,文本,是不一样的bytes,类型的8位字序列.要简单地从一个转换为另一个,您可以内联调用encode(就像您可以使用任何函数调用一样)...

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
Run Code Online (Sandbox Code Playgroud)

..请记住,指定要使用的编码通常是个好主意...

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('ascii'))
Run Code Online (Sandbox Code Playgroud)

...但是使用字节文字更简单.使用以下代码作为前缀b:

s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
Run Code Online (Sandbox Code Playgroud)

但你知道什么更简单吗?让其他人为你做HTTP.您是否考虑过使用Flask等服务器甚至是标准库来构建应用程序?