在Python中marshal對象序列化的相關知識

來源:互聯網
上載者:User

在Python中marshal對象序列化的相關知識

   這篇文章主要介紹了在Python中marshal對象序列化的相關知識,是Python進階學習中序列化相關的知識,需要的朋友可以參考下

  有時候,要把記憶體中的一個對象持久化儲存到磁碟上,或者序列化成二進位流通過網路發送到遠程主機上。Python中有很多模組提供了序列化與還原序列化的功能,如:marshal, pickle, cPickle等等。今天就講講marshal模組。

  注意: marshal並不是一個通用的模組,在某些時候它是一個不被推薦使用的模組,因為使用marshal序列化的位元據格式還沒有文檔化,在不同版本的Python中,marshal的實現可能不一樣。也就是說,用python2.5序列為一個對象,用python2.6的程式還原序列化所得到的對象,可能與原來的對象是不一樣的。但這個模組存在的意義,正如Python手冊中所說:The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files.

  下面是marshal模組中定義的一些與序列化/還原序列化有關的函數:

  marshal.dump(value, file[, version])

  將值寫入到一個開啟的輸出資料流裡。參數value表示待序列化的值。file表示開啟的輸出資料流。如:以”wb”模式開啟的檔案,sys.stdout或者os.popen。對於一些不支援序列類的類型,dump方法將拋出ValueError異常。要特別說明一下,並不是所有類型的對象都可以使用marshal模組來序列化/還原序列化的。在python2.6中,支援的類型包括:None, integers, long integers, floating point numbers, strings, Unicode objects, tuple, list, set, dict, 和 code objects。對於tuple, list, set, dict等集合對象,其中的元素必須也是上述類型之一。

  marshal.load(file)

  執行與marshal.dump相反的操作,將位元據反序列為Python對象。下面是一個例子,示範這兩個方法的使用:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

# coding=gbk

 

import marshal , sys , os

 

lst = [ 1 , ( 2 , " string " ) , { " key " : " Value " } ]

 

# 序列化到檔案中

fle = open ( os . path . join ( os . getcwd ( ) , ' fle . txt ' ) , ' wb ' )

marshal . dump ( lst , fle )

fle . close ( )

 

# 還原序列化

fle1 = open ( os . path . join ( os . getcwd ( ) , ' fle . txt ' ) , ' rb ' )

lst1 = marshal . load ( fle1 )

fle1 . close ( )

 

# 列印結果

print lst

print lst1

 

# ---- 結果 ----

# [1, (2, 'string'), {'key': 'Value'}]

# [1, (2, 'string'), {'key': 'Value'}]

marshal.dumps(value[, version)

  該方法與上面講的marshal.dump()功能類似,只是它返回的是序列化之後的二進位流,而不是將這些資料直接寫入到檔案中。

  marsahl.load(string)

  將二進位流還原序列化為對象。下面的一段代碼,示範這兩個方法的使用:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import marshal , sys , os

 

lst = [ 1 , ( 2 , " string " ) , { " key " : " Value " } ]

 

byt1 = marshal . dumps ( lst )

lst1 = marshal . loads ( byt1 )

 

# 列印結果

print lst

print lst1

 

# —- 結果 —-

# [1, (2, 'string'), {'key': 'Value'}]

# [1, (2, 'string'), {'key': 'Value'}]

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.