[b4a150]: / ReadersWriters / _PickleSerialised.py

Download this file

152 lines (136 with data), 5.6 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 2017 University of Westminster. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""It is an interface for serialising python objects and optionally compressing them.
"""
from typing import TypeVar, Any
import pickle
import bz2
import sys
import os
import logging
from Configs.CONSTANTS import CONSTANTS
OsStatResult = TypeVar('stat_result')
__author__ = "Mohsen Mesgarpour"
__copyright__ = "Copyright 2016, https://github.com/mesgarpour"
__credits__ = ["Mohsen Mesgarpour"]
__license__ = "GPL"
__version__ = "1.1"
__maintainer__ = "Mohsen Mesgarpour"
__email__ = "mohsen.mesgarpour@gmail.com"
__status__ = "Release"
class PickleSerialised:
def __init__(self):
"""Initialise the objects and constants."""
self.__logger = logging.getLogger(CONSTANTS.app_name)
self.__logger.debug(__name__)
self.__path = None
def set(self,
path: str,
title: str,
ext: str):
"""Set the python serialiser configuration settings.
:param path: the directory path of the serialised file.
:param title: the title of the output file.
:param ext: the extension of the output file.
"""
self.__logger.debug("Set the pickle file.")
self.__path = os.path.join(path, title + "." + ext)
self.__logger.debug(self.__path)
def exists(self) -> bool:
"""Check if the serialised object exists.
:return: indicates if the file exists.
"""
self.__logger.debug("Check if the pickle file exists.")
return os.path.isfile(self.__path)
def save(self,
objects: Any):
"""Serialise the object (Pickle protocol=4), without compression.
:param objects: the object to be saved.
"""
self.__logger.debug("Save the Pickle file.")
try:
with open(self.__path, 'wb') as f:
pickle.dump(objects, f, protocol=4)
except (OSError, IOError) as e:
self.__logger.error(__name__ + " - Can not open the file: \n" + self.__path + "\n")
print(e)
sys.exit()
except Exception as e:
self.__logger.error(__name__ + " - Unable to save data to: \n" + self.__path + "\n")
print(e)
sys.exit()
file_stats = os.stat(self.__path)
self.__logger.info("Pickle Size: " + str(file_stats.st_size) + ".")
def save_bz2(self,
objects: Any):
"""Serialise the object (Pickle protocol=4), then compress (BZ2 compression).
:param objects: the object to be saved.
"""
self.__logger.debug("Save the Pickle file and compress.")
try:
with bz2.BZ2File(self.__path, 'wb') as f:
pickle.dump(objects, f, protocol=4)
except (OSError, IOError) as e:
self.__logger.error(__name__ + " - Can not open the file: \n" + self.__path + "\n")
print(e)
sys.exit()
except Exception as e:
self.__logger.error(__name__ + " - Unable to save data to: \n" + self.__path + "\n")
print(e)
sys.exit()
file_stats = os.stat(self.__path)
self.__logger.info("Pickle Size: " + str(file_stats.st_size) + ".")
def load(self) -> Any:
"""Load a serialised object, that was not compressed.
:return: the loaded python object.
"""
self.__logger.debug("Load a Pickle file.")
try:
with open(self.__path, 'rb') as f:
objects = pickle.load(f)
except (OSError, IOError) as e:
self.__logger.error(__name__ + " - Can not open the file: \n" + self.__path + "\n")
print(e)
sys.exit()
except Exception as e:
self.__logger.error(__name__ + " - Unable to load data from: \n" + self.__path + "\n")
print(e)
sys.exit()
return objects
def load_bz2(self) -> Any:
"""Load a serialised object, that was compressed (BZ2 compression).
:return: the loaded python object.
"""
self.__logger.debug("Save a compressed Pickle file.")
try:
with bz2.BZ2File(self.__path, 'rb') as f:
objects = pickle.load(f)
except (OSError, IOError) as e:
self.__logger.error(__name__ + " - Can not open the file: \n" + self.__path + "\n")
print(e)
sys.exit()
except Exception as e:
self.__logger.error(__name__ + " - Unable to load data from \n" + self.__path + "\n")
print(e)
sys.exit()
return objects
def size(self) -> OsStatResult:
"""Check the size of the saved file.
:return: showing stat information of the file.
"""
return os.stat(self.__path)