We know that Python defines only 6 data types, string, Integer, floating point, list, tuple, and dictionary. But what are some of the byte-type variables in C that can be implemented in Python? This is important, especially if you want to transfer data over the network.
Python provides a struct module to provide conversions. Here are a few of the methods in this module.
The three most important functions in a struct module are pack (), unpack (), calcsize ()
# 按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)
pack(fmt,v1, v2, ...) #按照给定的格式(fmt)解析字节流string,返回解析出来的tupleunpack(fmt,string) #计算给定的格式(fmt)占用多少字节的内存
calcsize(fmt)
Reference:
Http://blog.sina.com.cn/s/blog_4b5039210100f1tu.html
My application (constructs Zabbix's request body):
def gen_request (self, jsons):
If Isinstance (Jsons, basestring):
data = '%s\n '% jsons
Else
data = Json.dumps (jsons)
Header = ' zbxd\x01 '
Datalen = Struct.pack (' Q ', Len (data))
Return header + Datalen + data
struct in Python