本文介绍了Python Gevent我看不到猴子打补丁默认文件打开/读取/写入/关闭,如何在gevent异步中制作文件io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在gevent猴子补丁中,我没有看到有关默认文件对象操作的任何信息.如何在基于gevent的程序中使用异步文件读/写?
In gevent monkey patch, I didn't see anything about default file object's operate.How can I use async file read/write in gevent based programs?
推荐答案
您可以使用gevent的fileobject.FileObjectThreadPool类,该类在1.0b3中可用:
You could use gevent's fileobject.FileObjectThreadPool class available in 1.0b3:
pip install http://gevent.googlecode.com/files/gevent-1.0b3.tar.gz#egg=gevent
那么您的示例将变为:
#!/usr/bin/env python
import gevent
from gevent.fileobject import FileObjectThreadPool
import datetime
def hi():
while True:
print datetime.datetime.now(), "Hello"
gevent.sleep( 1 )
def w():
print "writing..."
s = "*"*(1024*1024*1024)
print 'about to open'
f_raw = open( "./a.txt", "wb" )
f = FileObjectThreadPool(f_raw, 'wb')
f.write(s)
f.close()
print 'write done'
t1 = gevent.spawn(hi)
t2 = gevent.spawn(w)
ts = [t1,t2]
gevent.joinall( ts )
我看到带有该代码的以下输出:
I see the following output with that code:
writing...
about to open
2012-08-13 13:00:27.876202 Hello
2012-08-13 13:00:28.881119 Hello
2012-08-13 13:00:29.959642 Hello
...
2012-08-13 13:00:58.010001 Hello
2012-08-13 13:00:59.010146 Hello
2012-08-13 13:01:00.010248 Hello
write done
2012-08-13 13:01:01.469547 Hello
...
这篇关于Python Gevent我看不到猴子打补丁默认文件打开/读取/写入/关闭,如何在gevent异步中制作文件io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!