Created
June 4, 2012 05:45
-
-
Save lhwork/2866561 to your computer and use it in GitHub Desktop.
gevent-asyncfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding:utf-8 | |
import sys | |
import os | |
import fcntl | |
import gevent.hub | |
import gevent.socket | |
class _socketobject: | |
def __init__(self, fileno, timeout=None): | |
self.__timeout = timeout | |
self.__fileno = fileno | |
self.setblocking(0) | |
self._read_event = gevent.hub.get_hub().loop.io(self.__fileno, 1) | |
self._write_event = gevent.hub.get_hub().loop.io(self.__fileno, 2) | |
def send(self, data, flags=0): | |
gevent.socket.wait_write(self.__fileno, self.__timeout) | |
return os.write(self.__fileno, data) | |
def recv(self, bufsize, flags=0): | |
gevent.socket.wait_read(self.__fileno, self.__timeout) | |
return os.read(self.__fileno, bufsize) | |
def fileno(self): | |
return self.__fileno | |
def setblocking(self, flag): | |
fileflag = fcntl.fcntl(self.__fileno, fcntl.F_GETFL) | |
if not flag: | |
fileflag |= os.O_NONBLOCK | |
else: | |
fileflag &= ~os.O_NONBLOCK | |
fcntl.fcntl(self.__fileno, fcntl.F_SETFL, fileflag) | |
def close(self): | |
self.hub.cancel_wait(self._read_event, gevent.socket.cancel_wait_ex) | |
self.hub.cancel_wait(self._write_event, gevent.socket.cancel_wait_ex) | |
os.close(self.__fileno) | |
class AsyncFile(gevent.socket._fileobject): | |
def __init__(self, name, mode='r', buffering=None, timeout=None): | |
osflag, osmode = 0, 0777 | |
for c in mode: | |
if c == 'r': | |
osflag = os.O_RDONLY | |
elif c == 'w': | |
osflag = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | |
osmode = 0644 | |
elif c == 'a': | |
osflag = os.O_WRONLY | os.O_CREAT | os.O_APPEND | |
osmode = 0644 | |
elif c == '+': | |
osflag &= ~(os.O_RDONLY | os.O_WRONLY) | |
osmode |= os.O_RDWR | |
else: | |
pass | |
self.__fileno = os.open(name, osflag, osmode) | |
sock = _socketobject(self.__fileno, timeout) | |
gevent.socket._fileobject.__init__(self, sock, mode) | |
def main(): | |
print AsyncFile(__file__).readlines() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment