文章目錄
- marshal.dump(value, file[, version])
- marshal.load(file)
- marshal.dumps(value[, version)
- marsahl.load(string)
有時候,要把記憶體中的一個對象持久化儲存到磁碟上,或者序列化成二進位流通過網路發送到遠程主機上。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 |
# 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.dumps(value[, version)
該方法與上面講的marshal.dump()功能類似,只是它返回的是序列化之後的二進位流,而不是將這些資料直接寫入到檔案中。
marsahl.load(string)
將二進位流還原序列化為對象。下面的一段代碼,示範這兩個方法的使用:
| 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手冊。