【发布时间】:2021-10-03 20:59:35
【问题描述】:
最小可重现示例,我的代码中仅使用了goto_index()。其余的不言自明:
import pickle,os
def goto_index(idx_str,src,dest=False) :
'''Go to index :
1. Convert 1-based comma seperated digits in idx_str into 0-based list containing each index digit as int.
2. Starting from current position of src, iterate until index[0] matches current objec's position.
If matched, try to index the object as given. If not matched, function raises EOFError. If index illegal
in object function raises IndexError.If object found and index found in object, return value found and
seek src to begining of object @ index.
3. If dest is specified, all values until index will be copied to it from it's current position.
If element is not found in src, the result will be that all elements from src's current positon
to EOF are copied to dest.
'''
index = [int(subidx)-1 for subidx in idx_str.split(',')]
val = None
obj_cnt = -1 # 0-based count
try :
while True : # EOFError if index[0] >= EOF point
obj = pickle.load(src)
obj_cnt += 1
if obj_cnt == index[0] :
val = obj
for subidx in index[1::] :
val = val[subidx] # IndexError if index illegal
src.seek(-len(pickle.dumps(obj)),os.SEEK_CUR) # Seek to start of object at index
return val
elif dest : pickle.dump(obj,dest)
except (EOFError,IndexError) : raise # Caller will handle exceptions
def add_elements(f) :
pickle.dump('hello world',f)
pickle.dump('good morning',f)
pickle.dump('69 420',f)
pickle.dump('ending !',f)
def get_elements(f) :
elements = []
# Actual code similarly calls goto_index() in ascending order of indices, avoiding repeated seeks.
for idx_str in ('1','2','3') :
elements.append(goto_index(idx_str,f))
return elements
with open("tmp","wb+") as tmp :
add_elements(tmp)
print(', '.join(get_elements(tmp)))
'''Expected output : hello world, good morning, 69 420
Actual output : hello world, good morning, ending !
Issue : When asking for 3rd element, 3rd element skipped, 4th returned, why ?
'''
编辑:问题在于goto_index() 在每次通话时都将obj_cnt 设置为-1。如何缓解这种情况?
【问题讨论】:
标签: python python-3.x pickle seek