Created
March 10, 2013 04:00
-
-
Save pcdinh/5127068 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import os | |
| import sys | |
| import errno | |
| import fcntl | |
| def file_to_pipe(file, pipe): | |
| if file.closed: | |
| pipe.closed() | |
| return | |
| fcntl.fcntl(file, fcntl.F_SETFL, os.O_NONBLOCK) | |
| fno = file.fileno() | |
| wait = True | |
| while True: | |
| try: | |
| chunk = file.read(chunksize) | |
| if not chunk: | |
| break | |
| pipe.put(chunk) | |
| except IOError, e: | |
| if e[0] != errno.EAGAIN: | |
| raise | |
| sys.exc_clear() | |
| try: | |
| if wait: | |
| socket.wait_read(fno) | |
| except IOError, e: | |
| if e[0] != errno.EPERM: | |
| raise | |
| sys.exc_clear() | |
| wait = False | |
| if not wait: | |
| sleep() | |
| file.close() | |
| pipe.close() | |
| def pipe_to_file(pipe, file): | |
| if file.closed: | |
| return | |
| fcntl.fcntl(file, fcntl.F_SETFL, os.OS_NONBLOCK) | |
| fno = file.fileno() | |
| try: | |
| socket.wait_write(fno) | |
| except IOError, e: | |
| if e[0] != errno.EPERM: | |
| raise | |
| sys.exc_clear() | |
| wait = False | |
| else: | |
| wait = True | |
| for chunk in pipe: | |
| while chunk: | |
| try: | |
| written = os.write(fno, chunk) | |
| chunk = chunk[written:] | |
| except IOError, e: | |
| if e[0] != errno.EAGAIN: | |
| raise | |
| sys.exc_clear() | |
| except OSError, e: | |
| if not file.closed: | |
| raise | |
| sys.exc_clear() | |
| pipe.close() | |
| return | |
| if wait: | |
| socket.wait_write(fno) | |
| else: | |
| sleep(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment