Python 2 也包含相同的io
库。
用于from io import open
跨 Python 版本工作。
然后,您的 API 应该提供一个open()
等效的(称为open()
or make_stream()
),它使用io
类库来提供相同的功能。
您需要做的就是创建一个实现io.RawIOBase
ABC的类,然后根据需要使用库提供的其他类来添加缓冲和文本处理:
import io
class MyFileObjectWrapper(io.RawIOBase):
def __init__(self, *args):
# do what needs done
def close(self):
if not self.closed:
# close the underlying file
self.closed = True
# ... etc for what is needed (e.g. def read(self, maxbytes=None), etc.
def open(fileobj, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
# Mode parsing and validation adapted from the io/_iomodule.c module
reading, writing, appending, updating = False
text, binary, universal = False
for c in mode:
if c == 'r':
reading = True;
continue
if c == 'w':
writing = True;
continue
if c == 'a':
appending = True;
continue
if c == '+':
updating = True;
continue
if c == 't':
text = True;
continue
if c == 'b':
binary = True;
continue
if c == 'U':
universal = reading = True;
continue
raise ValueError('invalid mode: {!r}'.format(mode))
rawmode = []
if reading: rawmode.append('r')
if writing: rawmode.append('w')
if appending: rawmode.append('a')
if updating: rawmode.append('+')
rawmode = ''.join(rawmode)
if universal and (writing or appending):
raise ValueError("can't use U and writing mode at once")
if text and binary) {
raise ValueError("can't have text and binary mode at once")
if reading + writing + appending > 1:
raise ValueError("must have exactly one of read/write/append mode")
if binary
if encoding is not None:
raise ValueError("binary mode doesn't take an encoding argument")
if errors is not None:
raise ValueError("binary mode doesn't take an errors argument")
if newline is not None:
raise ValueError("binary mode doesn't take a newline argument")
raw = MyFileObjectWrapper(fileobj)
if buffering == 1:
buffering = -1
line_buffering = True
else:
line_buffering = False
if buffering < 0:
buffering = SOME_SUITABLE_DEFAULT
if not buffering
if not binary:
raise ValueError("can't have unbuffered text I/O")
return raw
if updating:
buffered_class = io.BufferedRandom
elif writing or appending:
buffered_class = io.BufferedWriter
elif reading:
buffered_class = io.BufferedReader
buffer = buffered_class(raw, buffering)
if binary:
return buffer
return io.TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
上面的代码大部分是从Modules/_io/_iomodule.c
io_open
函数改编而来的,但是将原始文件对象替换为ABC的MyFileObjectWrapper
子类。io.RawIOBase