4

在 gevent 猴子补丁中,我没有看到任何关于默认文件对象的操作。如何在基于 gevent 的程序中使用异步文件读/写?

4

3 回答 3

4

您可以使用 1.0b3 中提供的 gevent 的 fileobject.FileObjectThreadPool 类:

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 )

我看到带有该代码的以下输出:

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
...
于 2012-08-13T03:10:54.643 回答
1

刚做了个测试,说写大文件会阻塞事件循环

#!/usr/bin/env python
import gevent
import datetime


def hi():
    while True:
        print datetime.datetime.now(), "Hello"
        gevent.sleep( 1 )

def w():
    print "writing..."
    s = "*"*(1024*1024*1024)
    f = open( "e:/a.txt", "wb" )
    f.write(s)
    f.close()

t1 = gevent.spawn(hi)
t2 = gevent.spawn(w)
ts = [t1,t2]
gevent.joinall( ts )

结果是这样的:

e:\zPython\zTest>gevent.write.large.file.py
writing...  # wait a long time here
write done.
2012-07-16 09:53:23.784000 Hello
2012-07-16 09:53:24.786000 Hello
2012-07-16 09:53:25.788000 Hello
于 2012-07-16T01:53:56.333 回答
0

您可以使用线程池(从 gevent 1.0开始):

>>> import gevent.threadpool
>>> pool = gevent.threadpool.ThreadPool(5)
>>> pool.apply(w)
于 2012-07-16T05:24:56.653 回答