看看Queue 类,它是线程安全的。
from Queue import Queue
writeQueue = Queue()
在线程中
writeQueue.put(repr(some_object))
然后将其转储到文件中,
outFile = open(path,'w')
while writeQueue.qsize():
outFile.write(writeQueue.get())
outFile.flush()
outFile.close()
Queue 将接受任何 python 对象,因此如果您尝试执行打印到文件以外的其他操作,只需通过 Queue.put 存储来自工作线程的对象。
如果您需要在脚本的多次调用中拆分提交,您将需要一种将部分构建的提交缓存到磁盘的方法。为避免多个副本同时尝试写入文件,请使用lockfile 模块,可通过 pip 获得。我通常使用 json 对数据进行编码来实现这些目的,它支持序列化字符串、unicode、列表、数字和 dicts,并且比 pickle 更安全。
with lockfile.LockFile('/path/to/file.sql'):
fin=open('/path/to/file')
data=json.loads(fin.read())
data.append(newdata)
fin.close()
fout=open('/path/to/file','w')
fout.write(json.dumps(data))
fout.close()
请注意,根据操作系统功能,锁定和解锁文件以及为每个请求重写文件所花费的时间可能比您预期的要长。如果可能,请尝试仅附加到文件,因为这样会更快。此外,您可能希望使用客户端/服务器模型,其中每个“请求”都会启动一个工作脚本,该脚本连接到服务器进程并通过网络套接字转发数据。这回避了对锁定文件的需求;根据您正在谈论的数据量,它可能能够将它们全部保存在服务器进程的内存中,或者服务器可能需要将其序列化到磁盘并以这种方式将其传递给数据库。
WSGI 服务器示例:
from Queue import Queue
q=Queue()
def flushQueue():
with open(path,'w') as f:
while q.qsize():
f.write(q.get())
def application(env, start_response):
q.put("Hello World!")
if q.qsize() > 999:
flushQueue()
start_response('200 OK', [('Content-Type', 'text/html')])
return ["Hello!"]