hed*_*der 6 python pygame save pickle savestate
我正在用 pygame 制作一个绘图程序,我想在其中为用户提供一个选项,即保存程序的确切状态,然后在稍后重新加载它。在这一点上,我保存了我的 globals dict 的副本,然后迭代,酸洗每个对象。pygame 中有一些对象不能被pickle,但可以转换为字符串并通过这种方式进行pickle。我的代码已设置为执行此操作,但是通过引用访问了其中一些不可选择的对象。换句话说,它们不在全局字典中,但它们被全局字典中的对象引用。我想在这个递归中对它们进行腌制,但我不知道如何告诉 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
Run Code Online (Sandbox Code Playgroud)
简而言之:不要这样做。
酸洗应用程序中的所有内容是混乱的,并且可能会导致问题。从您的程序中获取您需要的数据并手动将其存储为适当的数据格式,然后通过从该数据中创建您需要的内容来加载它。