2
An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
4
Classes defined here: UnsupportedOperation, BlockingIOError.
5
Functions defined here: open().
7
Mostly written by Amaury Forgeot d'Arc
10
#define PY_SSIZE_T_CLEAN
12
#include "structmember.h"
13
#include "_iomodule.h"
15
#ifdef HAVE_SYS_TYPES_H
16
#include <sys/types.h>
17
#endif /* HAVE_SYS_TYPES_H */
19
#ifdef HAVE_SYS_STAT_H
21
#endif /* HAVE_SYS_STAT_H */
24
/* Various interned strings */
26
PyObject *_PyIO_str_close;
27
PyObject *_PyIO_str_closed;
28
PyObject *_PyIO_str_decode;
29
PyObject *_PyIO_str_encode;
30
PyObject *_PyIO_str_fileno;
31
PyObject *_PyIO_str_flush;
32
PyObject *_PyIO_str_getstate;
33
PyObject *_PyIO_str_isatty;
34
PyObject *_PyIO_str_newlines;
35
PyObject *_PyIO_str_nl;
36
PyObject *_PyIO_str_read;
37
PyObject *_PyIO_str_read1;
38
PyObject *_PyIO_str_readable;
39
PyObject *_PyIO_str_readinto;
40
PyObject *_PyIO_str_readline;
41
PyObject *_PyIO_str_reset;
42
PyObject *_PyIO_str_seek;
43
PyObject *_PyIO_str_seekable;
44
PyObject *_PyIO_str_tell;
45
PyObject *_PyIO_str_truncate;
46
PyObject *_PyIO_str_writable;
47
PyObject *_PyIO_str_write;
49
PyObject *_PyIO_empty_str;
50
PyObject *_PyIO_empty_bytes;
53
PyDoc_STRVAR(module_doc,
54
"The io module provides the Python interfaces to stream handling. The\n"
55
"builtin open function is defined in this module.\n"
57
"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
58
"defines the basic interface to a stream. Note, however, that there is no\n"
59
"seperation between reading and writing to streams; implementations are\n"
60
"allowed to throw an IOError if they do not support a given operation.\n"
62
"Extending IOBase is RawIOBase which deals simply with the reading and\n"
63
"writing of raw bytes to a stream. FileIO subc lasses RawIOBase to provide\n"
64
"an interface to OS files.\n"
66
"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
67
"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
68
"streams that are readable, writable, and both respectively.\n"
69
"BufferedRandom provides a buffered interface to random access\n"
70
"streams. BytesIO is a simple stream of in-memory bytes.\n"
72
"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
73
"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
74
"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
75
"is a in-memory stream for text.\n"
77
"Argument names are not part of the specification, and only the arguments\n"
78
"of open() are intended to be used as keyword arguments.\n"
82
"DEFAULT_BUFFER_SIZE\n"
84
" An int containing the default buffer size used by the module's buffered\n"
85
" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
91
* BlockingIOError extends IOError
95
BlockingIOError_init(PyBlockingIOErrorObject *self, PyObject *args,
98
PyObject *myerrno = NULL, *strerror = NULL;
99
PyObject *baseargs = NULL;
100
Py_ssize_t written = 0;
102
assert(PyTuple_Check(args));
105
if (!PyArg_ParseTuple(args, "OO|n:BlockingIOError",
106
&myerrno, &strerror, &written))
109
baseargs = PyTuple_Pack(2, myerrno, strerror);
110
if (baseargs == NULL)
112
/* This will take care of initializing of myerrno and strerror members */
113
if (((PyTypeObject *)PyExc_IOError)->tp_init(
114
(PyObject *)self, baseargs, kwds) == -1) {
120
self->written = written;
124
static PyMemberDef BlockingIOError_members[] = {
125
{"characters_written", T_PYSSIZET, offsetof(PyBlockingIOErrorObject, written), 0},
126
{NULL} /* Sentinel */
129
static PyTypeObject _PyExc_BlockingIOError = {
130
PyVarObject_HEAD_INIT(NULL, 0)
131
"BlockingIOError", /*tp_name*/
132
sizeof(PyBlockingIOErrorObject), /*tp_basicsize*/
141
0, /*tp_as_sequence*/
149
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
150
PyDoc_STR("Exception raised when I/O would block "
151
"on a non-blocking I/O stream"), /* tp_doc */
154
0, /* tp_richcompare */
155
0, /* tp_weaklistoffset */
159
BlockingIOError_members, /* tp_members */
163
0, /* tp_descr_get */
164
0, /* tp_descr_set */
165
0, /* tp_dictoffset */
166
(initproc)BlockingIOError_init, /* tp_init */
170
PyObject *PyExc_BlockingIOError = (PyObject *)&_PyExc_BlockingIOError;
174
* The main open() function
176
PyDoc_STRVAR(open_doc,
177
"Open file and return a stream. Raise IOError upon failure.\n"
179
"file is either a text or byte string giving the name (and the path\n"
180
"if the file isn't in the current working directory) of the file to\n"
181
"be opened or an integer file descriptor of the file to be\n"
182
"wrapped. (If a file descriptor is given, it is closed when the\n"
183
"returned I/O object is closed, unless closefd is set to False.)\n"
185
"mode is an optional string that specifies the mode in which the file\n"
186
"is opened. It defaults to 'r' which means open for reading in text\n"
187
"mode. Other common values are 'w' for writing (truncating the file if\n"
188
"it already exists), and 'a' for appending (which on some Unix systems,\n"
189
"means that all writes append to the end of the file regardless of the\n"
190
"current seek position). In text mode, if encoding is not specified the\n"
191
"encoding used is platform dependent. (For reading and writing raw\n"
192
"bytes use binary mode and leave encoding unspecified.) The available\n"
195
"========= ===============================================================\n"
196
"Character Meaning\n"
197
"--------- ---------------------------------------------------------------\n"
198
"'r' open for reading (default)\n"
199
"'w' open for writing, truncating the file first\n"
200
"'a' open for writing, appending to the end of the file if it exists\n"
202
"'t' text mode (default)\n"
203
"'+' open a disk file for updating (reading and writing)\n"
204
"'U' universal newline mode (for backwards compatibility; unneeded\n"
206
"========= ===============================================================\n"
208
"The default mode is 'rt' (open for reading text). For binary random\n"
209
"access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n"
210
"'r+b' opens the file without truncation.\n"
212
"Python distinguishes between files opened in binary and text modes,\n"
213
"even when the underlying operating system doesn't. Files opened in\n"
214
"binary mode (appending 'b' to the mode argument) return contents as\n"
215
"bytes objects without any decoding. In text mode (the default, or when\n"
216
"'t' is appended to the mode argument), the contents of the file are\n"
217
"returned as strings, the bytes having been first decoded using a\n"
218
"platform-dependent encoding or using the specified encoding if given.\n"
220
"buffering is an optional integer used to set the buffering policy. By\n"
221
"default full buffering is on. Pass 0 to switch buffering off (only\n"
222
"allowed in binary mode), 1 to set line buffering, and an integer > 1\n"
223
"for full buffering.\n"
225
"encoding is the name of the encoding used to decode or encode the\n"
226
"file. This should only be used in text mode. The default encoding is\n"
227
"platform dependent, but any encoding supported by Python can be\n"
228
"passed. See the codecs module for the list of supported encodings.\n"
230
"errors is an optional string that specifies how encoding errors are to\n"
231
"be handled---this argument should not be used in binary mode. Pass\n"
232
"'strict' to raise a ValueError exception if there is an encoding error\n"
233
"(the default of None has the same effect), or pass 'ignore' to ignore\n"
234
"errors. (Note that ignoring encoding errors can lead to data loss.)\n"
235
"See the documentation for codecs.register for a list of the permitted\n"
236
"encoding error strings.\n"
238
"newline controls how universal newlines works (it only applies to text\n"
239
"mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n"
242
"* On input, if newline is None, universal newlines mode is\n"
243
" enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n"
244
" these are translated into '\\n' before being returned to the\n"
245
" caller. If it is '', universal newline mode is enabled, but line\n"
246
" endings are returned to the caller untranslated. If it has any of\n"
247
" the other legal values, input lines are only terminated by the given\n"
248
" string, and the line ending is returned to the caller untranslated.\n"
250
"* On output, if newline is None, any '\\n' characters written are\n"
251
" translated to the system default line separator, os.linesep. If\n"
252
" newline is '', no translation takes place. If newline is any of the\n"
253
" other legal values, any '\\n' characters written are translated to\n"
254
" the given string.\n"
256
"If closefd is False, the underlying file descriptor will be kept open\n"
257
"when the file is closed. This does not work when a file name is given\n"
258
"and must be True in that case.\n"
260
"open() returns a file object whose type depends on the mode, and\n"
261
"through which the standard file operations such as reading and writing\n"
262
"are performed. When open() is used to open a file in a text mode ('w',\n"
263
"'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n"
264
"a file in a binary mode, the returned class varies: in read binary\n"
265
"mode, it returns a BufferedReader; in write binary and append binary\n"
266
"modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
267
"a BufferedRandom.\n"
269
"It is also possible to use a string or bytearray as a file for both\n"
270
"reading and writing. For strings StringIO can be used like a file\n"
271
"opened in a text mode, and for bytes a BytesIO can be used like a file\n"
272
"opened in a binary mode.\n"
276
io_open(PyObject *self, PyObject *args, PyObject *kwds)
278
char *kwlist[] = {"file", "mode", "buffering",
279
"encoding", "errors", "newline",
283
int buffering = -1, closefd = 1;
284
char *encoding = NULL, *errors = NULL, *newline = NULL;
287
int reading = 0, writing = 0, appending = 0, updating = 0;
288
int text = 0, binary = 0, universal = 0;
291
int line_buffering, isatty;
293
PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;
295
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist,
296
&file, &mode, &buffering,
297
&encoding, &errors, &newline,
302
if (!PyUnicode_Check(file) &&
303
!PyBytes_Check(file) &&
304
!PyNumber_Check(file)) {
305
PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
310
for (i = 0; i < strlen(mode); i++) {
340
/* c must not be duplicated */
341
if (strchr(mode+i+1, c)) {
343
PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
350
if (reading) *(m++) = 'r';
351
if (writing) *(m++) = 'w';
352
if (appending) *(m++) = 'a';
353
if (updating) *(m++) = '+';
356
/* Parameters validation */
358
if (writing || appending) {
359
PyErr_SetString(PyExc_ValueError,
360
"can't use U and writing mode at once");
366
if (text && binary) {
367
PyErr_SetString(PyExc_ValueError,
368
"can't have text and binary mode at once");
372
if (reading + writing + appending > 1) {
373
PyErr_SetString(PyExc_ValueError,
374
"must have exactly one of read/write/append mode");
378
if (binary && encoding != NULL) {
379
PyErr_SetString(PyExc_ValueError,
380
"binary mode doesn't take an encoding argument");
384
if (binary && errors != NULL) {
385
PyErr_SetString(PyExc_ValueError,
386
"binary mode doesn't take an errors argument");
390
if (binary && newline != NULL) {
391
PyErr_SetString(PyExc_ValueError,
392
"binary mode doesn't take a newline argument");
396
/* Create the Raw file stream */
397
raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
398
"Osi", file, rawmode, closefd);
402
modeobj = PyUnicode_FromString(mode);
408
PyObject *res = PyObject_CallMethod(raw, "isatty", NULL);
411
isatty = PyLong_AsLong(res);
413
if (isatty == -1 && PyErr_Occurred())
417
if (buffering == 1 || (buffering < 0 && isatty)) {
425
buffering = DEFAULT_BUFFER_SIZE;
426
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
430
PyObject *res = PyObject_CallMethod(raw, "fileno", NULL);
434
fileno = PyLong_AsLong(res);
436
if (fileno == -1 && PyErr_Occurred())
439
if (fstat(fileno, &st) >= 0)
440
buffering = st.st_blksize;
445
PyErr_SetString(PyExc_ValueError,
446
"invalid buffering size");
450
/* if not buffering, returns the raw file object */
451
if (buffering == 0) {
453
PyErr_SetString(PyExc_ValueError,
454
"can't have unbuffered text I/O");
462
/* wraps into a buffered file */
464
PyObject *Buffered_class;
467
Buffered_class = (PyObject *)&PyBufferedRandom_Type;
468
else if (writing || appending)
469
Buffered_class = (PyObject *)&PyBufferedWriter_Type;
471
Buffered_class = (PyObject *)&PyBufferedReader_Type;
473
PyErr_Format(PyExc_ValueError,
474
"unknown mode: '%s'", mode);
478
buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
485
/* if binary, returns the buffered file */
491
/* wraps into a TextIOWrapper */
492
wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
495
encoding, errors, newline,
501
if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0)
515
* Private helpers for the io module.
519
PyNumber_AsOff_t(PyObject *item, PyObject *err)
523
PyObject *value = PyNumber_Index(item);
527
/* We're done if PyLong_AsSsize_t() returns without error. */
528
result = PyLong_AsOff_t(value);
529
if (result != -1 || !(runerr = PyErr_Occurred()))
532
/* Error handling code -- only manage OverflowError differently */
533
if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
537
/* If no error-handling desired then the default clipping
541
assert(PyLong_Check(value));
542
/* Whether or not it is less than or equal to
543
zero is determined by the sign of ob_size
545
if (_PyLong_Sign(value) < 0)
546
result = PY_OFF_T_MIN;
548
result = PY_OFF_T_MAX;
551
/* Otherwise replace the error with caller's error object. */
553
"cannot fit '%.200s' into an offset-sized integer",
554
item->ob_type->tp_name);
563
iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
564
_PyIO_State *state = IO_MOD_STATE(mod);
565
if (!state->initialized)
567
Py_VISIT(state->os_module);
568
if (state->locale_module != NULL) {
569
Py_VISIT(state->locale_module);
571
Py_VISIT(state->unsupported_operation);
576
iomodule_clear(PyObject *mod) {
577
_PyIO_State *state = IO_MOD_STATE(mod);
578
if (!state->initialized)
580
Py_CLEAR(state->os_module);
581
if (state->locale_module != NULL)
582
Py_CLEAR(state->locale_module);
583
Py_CLEAR(state->unsupported_operation);
588
iomodule_free(PyObject *mod) {
596
static PyMethodDef module_methods[] = {
597
{"open", (PyCFunction)io_open, METH_VARARGS|METH_KEYWORDS, open_doc},
601
struct PyModuleDef _PyIO_Module = {
602
PyModuleDef_HEAD_INIT,
610
(freefunc)iomodule_free,
616
PyObject *m = PyModule_Create(&_PyIO_Module);
617
_PyIO_State *state = NULL;
620
state = IO_MOD_STATE(m);
621
state->initialized = 0;
623
/* put os in the module state */
624
state->os_module = PyImport_ImportModule("os");
625
if (state->os_module == NULL)
628
#define ADD_TYPE(type, name) \
629
if (PyType_Ready(type) < 0) \
632
if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
637
/* DEFAULT_BUFFER_SIZE */
638
if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
641
/* UnsupportedOperation inherits from ValueError and IOError */
642
state->unsupported_operation = PyObject_CallFunction(
643
(PyObject *)&PyType_Type, "s(OO){}",
644
"UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
645
if (state->unsupported_operation == NULL)
647
Py_INCREF(state->unsupported_operation);
648
if (PyModule_AddObject(m, "UnsupportedOperation",
649
state->unsupported_operation) < 0)
652
/* BlockingIOError */
653
_PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
654
ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");
656
/* Concrete base types of the IO ABCs.
657
(the ABCs themselves are declared through inheritance in io.py)
659
ADD_TYPE(&PyIOBase_Type, "_IOBase");
660
ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
661
ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
662
ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
664
/* Implementation of concrete IO objects. */
666
PyFileIO_Type.tp_base = &PyRawIOBase_Type;
667
ADD_TYPE(&PyFileIO_Type, "FileIO");
670
PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
671
ADD_TYPE(&PyBytesIO_Type, "BytesIO");
674
PyStringIO_Type.tp_base = &PyTextIOBase_Type;
675
ADD_TYPE(&PyStringIO_Type, "StringIO");
678
PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
679
ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
682
PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
683
ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
686
PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
687
ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
690
PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
691
ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
694
PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
695
ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
697
/* IncrementalNewlineDecoder */
698
ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
700
/* Interned strings */
701
if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
703
if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
705
if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
707
if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
709
if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
711
if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
713
if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
715
if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
717
if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
719
if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
721
if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
723
if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
725
if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
727
if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
729
if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
731
if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
733
if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
735
if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
737
if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
739
if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
741
if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
743
if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
746
if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
748
if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
751
state->initialized = 1;
756
Py_XDECREF(state->os_module);
757
Py_XDECREF(state->unsupported_operation);