有時候,要把記憶體中的一個物件持久化儲存到磁碟上,或者序列化成二進位制流通過網路傳送到遠端主機上。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 |
# 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'}] |
更多關於marshal的內容,請參考Python手冊。