python 处理python socket recv的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/691345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:39:20  来源:igfitidea点击:

Handling output of python socket recv

pythonsockets

提问by chrism1

Apologies for the noob Python question but I've been stuck on this for far too long.

对 noob Python 问题表示歉意,但我已经被困在这个问题上太久了。

I'm using python sockets to receive some data from a server. I do this:

我正在使用 python 套接字从服务器接收一些数据。我这样做:


data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)

The output on the console is this:

控制台上的输出是这样的:

data is
repr(data) is '\x00\x00\x00\x01'

数据是
repr(data) 是 '\x00\x00\x00\x01'

I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage?

我想将这个基本上包含 4 字节数字的字符串转换为 int - 或者实际上是 C 中的 long。如何将此数据对象转换为我可以轻松管理的数值?

回答by grieve

You probably want to use struct.

您可能想使用struct

The code would look something like:

代码如下所示:

import struct

data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
myint = struct.unpack("!i", data)[0]