marshal
--- 内部 Python 物件序列化¶
此 module(模組)包含一個能以二進位制格式來讀寫 Python 值的函式。這種格式是 Python 專屬但獨立於機器架構的(例如,你可以在一臺 PC 上寫入某個 Python 值,再將檔案傳到一臺 Mac 上並在那裡讀取它)。這種格式的細節是有意地不在文件上說明的;它可能在不同 Python 版本中被改變(雖然這種情況極少發生)。[1]
這不是一個通用「持續性 (persistence)」module 。關於通用持續性以及透過 RPC 呼叫傳遞 Python 物件,請參閱 pickle
和 shelve
等 module 。marshal
module 主要是為了支援用來讀寫「偽編譯 (pseudo-compiled)」 .pyc
檔案的 Python module。因此,Python 維護者保留了在必要時以不向後相容的方式修改 marshal 格式的權利。如果你要序列化和反序列化 Python 物件,請改用 pickle
module -- 其執行效率相當、有保證版本獨立性,且實質上 pickle 還支援比 marshal 更多樣的物件。
警告
marshal
module 對於錯誤或惡意構建的資料來說是不安全的。永遠不要 unmarshal 來自不受信任的或來源未經驗證的資料。
Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by
this module. The following types are supported: booleans, integers, floating-point
numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets,
frozensets, dictionaries, and code objects, where it should be understood that
tuples, lists, sets, frozensets and dictionaries are only supported as long as
the values contained therein are themselves supported. The
singletons None
, Ellipsis
and StopIteration
can also be
marshalled and unmarshalled.
For format version lower than 3, recursive lists, sets and dictionaries cannot
be written (see below).
有些函式可以讀/寫檔案,還有些函式可以操作類位元組串物件 (bytes-like object)。
這個 module 定義了以下函式:
- marshal.dump(value, file[, version])¶
將值寫入被開啟的檔案。值必須為受支援的型別,檔案必須為可寫入的 binary file。
如果值具有(或其所包含的物件具有)不支援的型別,則會引發
ValueError
例外 --- 但是垃圾資料 (garbage data) 也將寫入檔案,物件也無法正確地透過load()
重新讀取。version 引數指明
dump
應該使用的資料格式(見下文)。引發一個附帶引數
value
與version
的稽核事件 (auditing event)marshal.dumps
。
- marshal.load(file)¶
從開啟的檔案讀取一個值並回傳。如果讀不到有效的值(例如,由於資料為不同 Python 版本的不相容 marshal 格式),則會引發
EOFError
、ValueError
或TypeError
。檔案必須為可讀取的 binary file。引發一個沒有附帶引數的稽核事件
marshal.load
。在 3.10 版的變更: 使用此呼叫為每個程式碼物件引發一個
code.__new__
稽核事件。現在它會為整個載入操作引發單個marshal.load
事件。
- marshal.dumps(value[, version])¶
回傳將透過
dump(value, file)
來被寫入一個檔案的位元組串物件,其值必須是有支援的型別,如果值(或其包含的任一物件)為不支援的型別則會引發ValueError
。version 引數指明
dumps
應當使用的資料型別(見下文)。引發一個附帶引數
value
與version
的稽核事件 (auditing event)marshal.dumps
。
- marshal.loads(bytes)¶
將 bytes-like object 轉換為一個值。如果找不到有效的值,則會引發
EOFError
、ValueError
或TypeError
。輸入中額外的位元組串會被忽略。引發一個附帶引數
bytes
的稽核事件marshal.loads
。在 3.10 版的變更: 使用此呼叫為每個程式碼物件引發一個
code.__new__
稽核事件。現在它會為整個載入操作引發單個marshal.loads
事件。
此外,還定義了以下常數:
- marshal.version¶
Indicates the format that the module uses. Version 0 is the historical format, version 1 shares interned strings and version 2 uses a binary format for floating-point numbers. Version 3 adds support for object instancing and recursion. The current version is 4.
註解