[英]How can I store many variables in one file, and access those variables from a different file?
I want to create a 'mini-database'. 我想创建一个'迷你数据库'。 I want to have one file with lots of variables, and be able to take those variables from the file, while also being able to add variables to the file?
我想要一个包含大量变量的文件,并且能够从文件中获取这些变量,同时还能够将变量添加到文件中吗? For example, lets suppose this is the 'mini-db':
例如,假设这是'mini-db':
hello = ['a', 'b', 'c']
world = ['d', 'e', 'f']
foo = ['g', 'h', 'i']
and from a different file, I would like to say something like: 从另一个文件,我想说:
print MiniDB.hello[0]
So basically access the variable. 所以基本上访问变量。 Also, I would need to write variables INTO the file.
另外,我需要在文件中写入变量INTO。 so something like this:
所以这样的事情:
MiniDB.bar = ['j', 'k', 'l']
How can I do this? 我怎样才能做到这一点?
This may not be what you are looking for, but this class allows storing program settings. 这可能不是您要找的,但此类允许存储程序设置。 You load it with default settings that represent the variables you need and embed dictionaries to generate namespaces.
您可以使用表示所需变量的默认设置加载它,并嵌入字典以生成名称空间。 It is not perfect, but tries to allow multiple database definitions to coexist with each other while ensuring data types do not change.
它并不完美,但尝试允许多个数据库定义相互共存,同时确保数据类型不会发生变化。 It has a limited field of usage but may act as the solution you require.
它的使用范围有限,但可以作为您需要的解决方案。
import copy
import pprint
import pickle
################################################################################
class _Interface:
def __init__(self, default, database=None):
self.__default = default
if database is None:
self.__database = copy.deepcopy(default)
else:
self.__database = database
def __repr__(self):
return pprint.pformat(self.__database)
def __getattr__(self, name):
attr = self.__default[name]
if isinstance(attr, dict):
return _Interface(attr, self.__database[name])
raise AttributeError(name)
def __setattr__(self, name, value):
if name in {'_Interface__default', '_Interface__database'}:
super().__setattr__(name, value)
else:
raise AttributeError(name)
def __getitem__(self, name):
item = self.__default[name]
if isinstance(item, dict):
raise KeyError(name)
return self.__database[name]
def __setitem__(self, name, value):
item = self.__default[name]
if isinstance(value, type(item)):
self.__database[name] = value
else:
raise TypeError(type(value))
################################################################################
class Registry(_Interface):
@property
def __database(self):
return self._Interface__database
def load(self, path):
with open(path, 'rb') as file:
data = pickle.load(file)
self.__merge(data, self.__database)
@classmethod
def __merge(cls, source, sink):
for key, value in source.items():
if key not in sink:
sink[key] = value
elif isinstance(value, type(sink[key])):
if isinstance(value, dict):
cls.__merge(value, sink[key])
else:
sink[key] = value
def save(self, path):
with open(path, 'wb') as file:
pickle.dump(self.__database, file)
################################################################################
file1 = Registry({'hello': ['a', 'b', 'c'],
'world': ['d', 'e', 'f'],
'foo': ['g', 'h', 'i'],
'namespace': {'j': 0,
'k': 1,
'm': '2',
'n': '3'}})
file2 = Registry({'hello': ['a', 'b', 'c'],
'world': ['d', 'e', 'f'],
'foo': ['g', 'h', 'i'],
'namespace': {'j': '4',
'k': '5',
'm': '6',
'n': '7'},
'bar': []})
file1['hello'][0] = 'z'
file1.save('mini.db')
file2.load('mini.db')
file2['bar'].extend(['j', 'k', 'l'])
print(file2)
print(file2.namespace['k'])
print(file2.namespace['m'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.