从为并发检查描述的解决方案的启发中,我想到了以下代码片段。如果人们能够适当地预测所讨论文件的写入频率,它就可以工作。解决方案是通过使用文件修改时间。
import osimport time'''Find if a file was modified in the last x seconds given by writeFrequency.'''def isFileBeingWrittenInto(filename, writeFrequency = 180, overheadTimePercentage = 20): overhead = 1+float(overheadTimePercentage)/100 # Add some buffer time maxWriteFrequency = writeFrequency * overhead modifiedTimeStart = os.stat(filename).st_mtime # Time file last modified time.sleep(writeFrequency) # wait writeFrequency # of secs modifiedTimeEnd = os.stat(filename).st_mtime # File modification time again if 0 < (modifiedTimeEnd - modifiedTimeStart) <= maxWriteFrequency: return True else: return Falseif not isFileBeingWrittenInto('fileForSafeWrites.txt'): handle = open('fileForSafeWrites.txt', 'a') handle.write("Text written safely when no one else is writing to the file") handle.close()
这并不能进行真正的并发检查,但是可以结合多种其他方法用于实际目的,以安全地写入文件而不必担心文本乱码。希望它可以帮助下一个寻找方法的人。
编辑更新 :
经过进一步测试,我遇到了高频写入过程,该过程要求修改条件逻辑。
if 0 < (modifiedTimeEnd - modifiedTimeStart) < maxWriteFrequency
至
if 0 < (modifiedTimeEnd - modifiedTimeStart) <= maxWriteFrequency
从理论上和实践上,这都是一个更好的答案。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)