我正在使用 pygame 制作一个绘图程序,我想在其中为用户提供一个选项,即保存程序的确切状态,然后在以后重新加载它。在这一点上,我保存了我的 globals dict 的副本,然后遍历,腌制每个对象。pygame 中有一些对象不能被腌制,但可以转换成字符串并以这种方式腌制。我的代码设置为执行此操作,但其中一些不可提取的对象是通过引用到达的。换句话说,它们不在全局字典中,但它们被全局字典中的对象引用。我想在这个递归中腌制它们,但我不知道如何告诉 pickle 返回它遇到问题的对象,更改它,然后尝试再次腌制它。我的代码真的很混乱,如果有一种不同的、更好的方式来做我的事情
surfaceStringHeader = 'PYGAME.SURFACE_CONVERTED:'
imageToStringFormat = 'RGBA'
def save_project(filename=None):
assert filename != None, "Please specify path of project file"
pickler = pickle.Pickler(file(filename,'w'))
for key, value in globals().copy().iteritems():
#There's a bit of a kludge statement here since I don't know how to
#access module type object directly
if type(value) not in [type(sys),type(None)] and \
key not in ['__name__','value','key'] and \
(key,value) not in pygame.__dict__.iteritems() and \
(key,value) not in sys.__dict__.iteritems() and \
(key,value) not in pickle.__dict__.iteritems():
#Perhaps I should add something to the above to reduce redundancy of
#saving the program defaults?
#Refromat unusable objects:
if type(value)==pygame.Surface:
valueString = pygame.image.tostring(value,imageToStringFormat)
widthString = str(value.get_size()[0]).zfill(5)
heightString = str(value.get_size()[1]).zfill(5)
formattedValue = surfaceStringHeader+widthString+heightString+valueString
else:
formattedValue = value
try:
pickler.dump((key,formattedValue))
except Exception as e:
print key+':' + str(e)
def open_project(filename=None):
assert filename != None, "Please specify path to project file"
unpickler = pickle.Unpickler(file(filename,'r'))
haventReachedEOF = False
while haventReachedEOF:
try:
key,value = unpickler.load()
#Rework the unpicklable objects stored
if type(value) == str and value[0:25]==surfaceStringHeader:
value = pygame.image.frombuffer(value[36:],(int(value[26:31]),int(value[31:36])),imageToStringFormat)
sys.modules['__main__'].__setattr__(key,value)
except EOFError:
haventReachedEOF = True