python中的struct

來源:互聯網
上載者:User

標籤:python struct

我們知道python只定義了6種資料類型,字串,整數,浮點數,列表,元組,字典。但是C語言中有些位元組型的變數,在python中該如何?呢?這點頗為重要,特別是要在網路上進行資料轉送的話。

python提供了一個struct模組來提供轉換。下面就介紹這個模組中的幾個方法。

struct模組中最重要的三個函數是pack(), unpack(), calcsize()


# 按照給定的格式(fmt),把資料封裝成字串(實際上是類似於c結構體的位元組流)

pack(fmt,v1, v2, ...)  #按照給定的格式(fmt)解析位元組流string,返回解析出來的tupleunpack(fmt,string)        #計算給定的格式(fmt)佔用多少位元組的記憶體

calcsize(fmt)



參考:

http://blog.sina.com.cn/s/blog_4b5039210100f1tu.html


我的應用程式(構造zabbix的請求體):

    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



python中的struct

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.