有時候,要把內存中的一個對象持久化保存到磁盤上,或者序列化成二進制流經過網絡發送到遠程主機上。Python中有不少模塊提供了序列化與反序列化的功能,如:marshal, pickle, cPickle等等。今天就講講marshal模塊。python
注意: 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模塊中定義的一些與序列化/反序列化有關的函數:ide
將值寫入到一個打開的輸出流裏。參數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.dump相反的操做,將二進制數據反序列爲Python對象。下面是一個例子,演示這兩個方法的使用:spa
1 | # coding=gbk |
2 | |
3 | import marshal , sys , os |
4 | |
5 | lst = [ 1 , ( 2 , " string " ) , { " key " : " Value " } ] |
6 | |
7 | # 序列化到文件中 |
8 | fle = open ( os . path . join ( os . getcwd ( ) , ' fle . txt ' ) , 'wb ' ) |
9 | marshal . dump ( lst , fle ) |
10 | fle . close ( ) |
11 | |
12 | # 反序列化 |
13 | fle1 = open ( os . path . join ( os . getcwd ( ) , ' fle . txt ' ) , 'rb ' ) |
14 | lst1 = marshal . load ( fle1 ) |
15 | fle1 . close ( ) |
16 | |
17 | # 打印結果 |
18 | print lst |
19 | print lst1 |
20 | |
21 | # ---- 結果 ---- |
22 | # [1, (2, 'string'), {'key': 'Value'}] |
23 | # [1, (2, 'string'), {'key': 'Value'}] |
該方法與上面講的marshal.dump()功能相似,只是它返回的是序列化以後的二進制流,而不是將這些數據直接寫入到文件中。code
將二進制流反序列化爲對象。下面的一段代碼,演示這兩個方法的使用:對象
1 | import marshal , sys , os |
2 | |
3 | lst = [ 1 , ( 2 , " string " ) , { " key " : " Value " } ] |
4 | |
5 | byt1 = marshal . dumps ( lst ) |
6 | lst1 = marshal . loads ( byt1 ) |
7 | |
8 | # 打印結果 |
9 | print lst |
10 | print lst1 |
11 | |
12 | # ---- 結果 ---- |
13 | # [1, (2, 'string'), {'key': 'Value'}] |
14 | # [1, (2, 'string'), {'key': 'Value'}] |
更多關於marshal的內容,請參考Python手冊。內存