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_setstate
;
45 PyObject
*_PyIO_str_tell
;
46 PyObject
*_PyIO_str_truncate
;
47 PyObject
*_PyIO_str_writable
;
48 PyObject
*_PyIO_str_write
;
50 PyObject
*_PyIO_empty_str
;
51 PyObject
*_PyIO_empty_bytes
;
55 PyDoc_STRVAR(module_doc
,
56 "The io module provides the Python interfaces to stream handling. The\n"
57 "builtin open function is defined in this module.\n"
59 "At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
60 "defines the basic interface to a stream. Note, however, that there is no\n"
61 "seperation between reading and writing to streams; implementations are\n"
62 "allowed to throw an IOError if they do not support a given operation.\n"
64 "Extending IOBase is RawIOBase which deals simply with the reading and\n"
65 "writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
66 "an interface to OS files.\n"
68 "BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
69 "subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
70 "streams that are readable, writable, and both respectively.\n"
71 "BufferedRandom provides a buffered interface to random access\n"
72 "streams. BytesIO is a simple stream of in-memory bytes.\n"
74 "Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
75 "of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
76 "interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
77 "is a in-memory stream for text.\n"
79 "Argument names are not part of the specification, and only the arguments\n"
80 "of open() are intended to be used as keyword arguments.\n"
84 "DEFAULT_BUFFER_SIZE\n"
86 " An int containing the default buffer size used by the module's buffered\n"
87 " I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
93 * BlockingIOError extends IOError
97 blockingioerror_init(PyBlockingIOErrorObject
*self
, PyObject
*args
,
100 PyObject
*myerrno
= NULL
, *strerror
= NULL
;
101 PyObject
*baseargs
= NULL
;
102 Py_ssize_t written
= 0;
104 assert(PyTuple_Check(args
));
107 if (!PyArg_ParseTuple(args
, "OO|n:BlockingIOError",
108 &myerrno
, &strerror
, &written
))
111 baseargs
= PyTuple_Pack(2, myerrno
, strerror
);
112 if (baseargs
== NULL
)
114 /* This will take care of initializing of myerrno and strerror members */
115 if (((PyTypeObject
*)PyExc_IOError
)->tp_init(
116 (PyObject
*)self
, baseargs
, kwds
) == -1) {
122 self
->written
= written
;
126 static PyMemberDef blockingioerror_members
[] = {
127 {"characters_written", T_PYSSIZET
, offsetof(PyBlockingIOErrorObject
, written
), 0},
128 {NULL
} /* Sentinel */
131 static PyTypeObject _PyExc_BlockingIOError
= {
132 PyVarObject_HEAD_INIT(NULL
, 0)
133 "BlockingIOError", /*tp_name*/
134 sizeof(PyBlockingIOErrorObject
), /*tp_basicsize*/
143 0, /*tp_as_sequence*/
151 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
152 PyDoc_STR("Exception raised when I/O would block "
153 "on a non-blocking I/O stream"), /* tp_doc */
156 0, /* tp_richcompare */
157 0, /* tp_weaklistoffset */
161 blockingioerror_members
, /* tp_members */
165 0, /* tp_descr_get */
166 0, /* tp_descr_set */
167 0, /* tp_dictoffset */
168 (initproc
)blockingioerror_init
, /* tp_init */
172 PyObject
*PyExc_BlockingIOError
= (PyObject
*)&_PyExc_BlockingIOError
;
176 * The main open() function
178 PyDoc_STRVAR(open_doc
,
179 "Open file and return a stream. Raise IOError upon failure.\n"
181 "file is either a text or byte string giving the name (and the path\n"
182 "if the file isn't in the current working directory) of the file to\n"
183 "be opened or an integer file descriptor of the file to be\n"
184 "wrapped. (If a file descriptor is given, it is closed when the\n"
185 "returned I/O object is closed, unless closefd is set to False.)\n"
187 "mode is an optional string that specifies the mode in which the file\n"
188 "is opened. It defaults to 'r' which means open for reading in text\n"
189 "mode. Other common values are 'w' for writing (truncating the file if\n"
190 "it already exists), and 'a' for appending (which on some Unix systems,\n"
191 "means that all writes append to the end of the file regardless of the\n"
192 "current seek position). In text mode, if encoding is not specified the\n"
193 "encoding used is platform dependent. (For reading and writing raw\n"
194 "bytes use binary mode and leave encoding unspecified.) The available\n"
197 "========= ===============================================================\n"
198 "Character Meaning\n"
199 "--------- ---------------------------------------------------------------\n"
200 "'r' open for reading (default)\n"
201 "'w' open for writing, truncating the file first\n"
202 "'a' open for writing, appending to the end of the file if it exists\n"
204 "'t' text mode (default)\n"
205 "'+' open a disk file for updating (reading and writing)\n"
206 "'U' universal newline mode (for backwards compatibility; unneeded\n"
208 "========= ===============================================================\n"
210 "The default mode is 'rt' (open for reading text). For binary random\n"
211 "access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n"
212 "'r+b' opens the file without truncation.\n"
214 "Python distinguishes between files opened in binary and text modes,\n"
215 "even when the underlying operating system doesn't. Files opened in\n"
216 "binary mode (appending 'b' to the mode argument) return contents as\n"
217 "bytes objects without any decoding. In text mode (the default, or when\n"
218 "'t' is appended to the mode argument), the contents of the file are\n"
219 "returned as strings, the bytes having been first decoded using a\n"
220 "platform-dependent encoding or using the specified encoding if given.\n"
222 "buffering is an optional integer used to set the buffering policy. By\n"
223 "default full buffering is on. Pass 0 to switch buffering off (only\n"
224 "allowed in binary mode), 1 to set line buffering, and an integer > 1\n"
225 "for full buffering.\n"
227 "encoding is the name of the encoding used to decode or encode the\n"
228 "file. This should only be used in text mode. The default encoding is\n"
229 "platform dependent, but any encoding supported by Python can be\n"
230 "passed. See the codecs module for the list of supported encodings.\n"
232 "errors is an optional string that specifies how encoding errors are to\n"
233 "be handled---this argument should not be used in binary mode. Pass\n"
234 "'strict' to raise a ValueError exception if there is an encoding error\n"
235 "(the default of None has the same effect), or pass 'ignore' to ignore\n"
236 "errors. (Note that ignoring encoding errors can lead to data loss.)\n"
237 "See the documentation for codecs.register for a list of the permitted\n"
238 "encoding error strings.\n"
240 "newline controls how universal newlines works (it only applies to text\n"
241 "mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n"
244 "* On input, if newline is None, universal newlines mode is\n"
245 " enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n"
246 " these are translated into '\\n' before being returned to the\n"
247 " caller. If it is '', universal newline mode is enabled, but line\n"
248 " endings are returned to the caller untranslated. If it has any of\n"
249 " the other legal values, input lines are only terminated by the given\n"
250 " string, and the line ending is returned to the caller untranslated.\n"
252 "* On output, if newline is None, any '\\n' characters written are\n"
253 " translated to the system default line separator, os.linesep. If\n"
254 " newline is '', no translation takes place. If newline is any of the\n"
255 " other legal values, any '\\n' characters written are translated to\n"
256 " the given string.\n"
258 "If closefd is False, the underlying file descriptor will be kept open\n"
259 "when the file is closed. This does not work when a file name is given\n"
260 "and must be True in that case.\n"
262 "open() returns a file object whose type depends on the mode, and\n"
263 "through which the standard file operations such as reading and writing\n"
264 "are performed. When open() is used to open a file in a text mode ('w',\n"
265 "'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n"
266 "a file in a binary mode, the returned class varies: in read binary\n"
267 "mode, it returns a BufferedReader; in write binary and append binary\n"
268 "modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
269 "a BufferedRandom.\n"
271 "It is also possible to use a string or bytearray as a file for both\n"
272 "reading and writing. For strings StringIO can be used like a file\n"
273 "opened in a text mode, and for bytes a BytesIO can be used like a file\n"
274 "opened in a binary mode.\n"
278 io_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
280 char *kwlist
[] = {"file", "mode", "buffering",
281 "encoding", "errors", "newline",
285 int buffering
= -1, closefd
= 1;
286 char *encoding
= NULL
, *errors
= NULL
, *newline
= NULL
;
289 int reading
= 0, writing
= 0, appending
= 0, updating
= 0;
290 int text
= 0, binary
= 0, universal
= 0;
293 int line_buffering
, isatty
;
295 PyObject
*raw
, *modeobj
= NULL
, *buffer
= NULL
, *wrapper
= NULL
;
297 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|sizzzi:open", kwlist
,
298 &file
, &mode
, &buffering
,
299 &encoding
, &errors
, &newline
,
304 if (!PyUnicode_Check(file
) &&
305 !PyBytes_Check(file
) &&
306 !PyNumber_Check(file
)) {
307 PyObject
*repr
= PyObject_Repr(file
);
309 PyErr_Format(PyExc_TypeError
, "invalid file: %s",
310 PyString_AS_STRING(repr
));
317 for (i
= 0; i
< strlen(mode
); i
++) {
347 /* c must not be duplicated */
348 if (strchr(mode
+i
+1, c
)) {
350 PyErr_Format(PyExc_ValueError
, "invalid mode: '%s'", mode
);
357 if (reading
) *(m
++) = 'r';
358 if (writing
) *(m
++) = 'w';
359 if (appending
) *(m
++) = 'a';
360 if (updating
) *(m
++) = '+';
363 /* Parameters validation */
365 if (writing
|| appending
) {
366 PyErr_SetString(PyExc_ValueError
,
367 "can't use U and writing mode at once");
373 if (text
&& binary
) {
374 PyErr_SetString(PyExc_ValueError
,
375 "can't have text and binary mode at once");
379 if (reading
+ writing
+ appending
> 1) {
380 PyErr_SetString(PyExc_ValueError
,
381 "must have exactly one of read/write/append mode");
385 if (binary
&& encoding
!= NULL
) {
386 PyErr_SetString(PyExc_ValueError
,
387 "binary mode doesn't take an encoding argument");
391 if (binary
&& errors
!= NULL
) {
392 PyErr_SetString(PyExc_ValueError
,
393 "binary mode doesn't take an errors argument");
397 if (binary
&& newline
!= NULL
) {
398 PyErr_SetString(PyExc_ValueError
,
399 "binary mode doesn't take a newline argument");
403 /* Create the Raw file stream */
404 raw
= PyObject_CallFunction((PyObject
*)&PyFileIO_Type
,
405 "Osi", file
, rawmode
, closefd
);
409 modeobj
= PyUnicode_FromString(mode
);
415 PyObject
*res
= PyObject_CallMethod(raw
, "isatty", NULL
);
418 isatty
= PyLong_AsLong(res
);
420 if (isatty
== -1 && PyErr_Occurred())
424 if (buffering
== 1 || (buffering
< 0 && isatty
)) {
432 buffering
= DEFAULT_BUFFER_SIZE
;
433 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
437 PyObject
*res
= PyObject_CallMethod(raw
, "fileno", NULL
);
441 fileno
= PyInt_AsLong(res
);
443 if (fileno
== -1 && PyErr_Occurred())
446 if (fstat(fileno
, &st
) >= 0)
447 buffering
= st
.st_blksize
;
452 PyErr_SetString(PyExc_ValueError
,
453 "invalid buffering size");
457 /* if not buffering, returns the raw file object */
458 if (buffering
== 0) {
460 PyErr_SetString(PyExc_ValueError
,
461 "can't have unbuffered text I/O");
469 /* wraps into a buffered file */
471 PyObject
*Buffered_class
;
474 Buffered_class
= (PyObject
*)&PyBufferedRandom_Type
;
475 else if (writing
|| appending
)
476 Buffered_class
= (PyObject
*)&PyBufferedWriter_Type
;
478 Buffered_class
= (PyObject
*)&PyBufferedReader_Type
;
480 PyErr_Format(PyExc_ValueError
,
481 "unknown mode: '%s'", mode
);
485 buffer
= PyObject_CallFunction(Buffered_class
, "Oi", raw
, buffering
);
492 /* if binary, returns the buffered file */
498 /* wraps into a TextIOWrapper */
499 wrapper
= PyObject_CallFunction((PyObject
*)&PyTextIOWrapper_Type
,
502 encoding
, errors
, newline
,
508 if (PyObject_SetAttrString(wrapper
, "mode", modeobj
) < 0)
522 * Private helpers for the io module.
526 PyNumber_AsOff_t(PyObject
*item
, PyObject
*err
)
530 PyObject
*value
= PyNumber_Index(item
);
534 if (PyInt_Check(value
)) {
535 /* We assume a long always fits in a Py_off_t... */
536 result
= (Py_off_t
) PyInt_AS_LONG(value
);
540 /* We're done if PyLong_AsSsize_t() returns without error. */
541 result
= PyLong_AsOff_t(value
);
542 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
545 /* Error handling code -- only manage OverflowError differently */
546 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
550 /* If no error-handling desired then the default clipping
554 assert(PyLong_Check(value
));
555 /* Whether or not it is less than or equal to
556 zero is determined by the sign of ob_size
558 if (_PyLong_Sign(value
) < 0)
559 result
= PY_OFF_T_MIN
;
561 result
= PY_OFF_T_MAX
;
564 /* Otherwise replace the error with caller's error object. */
566 "cannot fit '%.200s' into an offset-sized integer",
567 item
->ob_type
->tp_name
);
580 PyObject
*_PyIO_os_module
= NULL
;
581 PyObject
*_PyIO_locale_module
= NULL
;
582 PyObject
*_PyIO_unsupported_operation
= NULL
;
584 static PyMethodDef module_methods
[] = {
585 {"open", (PyCFunction
)io_open
, METH_VARARGS
|METH_KEYWORDS
, open_doc
},
592 PyObject
*m
= Py_InitModule4("_io", module_methods
,
593 module_doc
, NULL
, PYTHON_API_VERSION
);
597 /* put os in the module state */
598 _PyIO_os_module
= PyImport_ImportModule("os");
599 if (_PyIO_os_module
== NULL
)
602 #define ADD_TYPE(type, name) \
603 if (PyType_Ready(type) < 0) \
606 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
611 /* DEFAULT_BUFFER_SIZE */
612 if (PyModule_AddIntMacro(m
, DEFAULT_BUFFER_SIZE
) < 0)
615 /* UnsupportedOperation inherits from ValueError and IOError */
616 _PyIO_unsupported_operation
= PyObject_CallFunction(
617 (PyObject
*)&PyType_Type
, "s(OO){}",
618 "UnsupportedOperation", PyExc_ValueError
, PyExc_IOError
);
619 if (_PyIO_unsupported_operation
== NULL
)
621 Py_INCREF(_PyIO_unsupported_operation
);
622 if (PyModule_AddObject(m
, "UnsupportedOperation",
623 _PyIO_unsupported_operation
) < 0)
626 /* BlockingIOError */
627 _PyExc_BlockingIOError
.tp_base
= (PyTypeObject
*) PyExc_IOError
;
628 ADD_TYPE(&_PyExc_BlockingIOError
, "BlockingIOError");
630 /* Concrete base types of the IO ABCs.
631 (the ABCs themselves are declared through inheritance in io.py)
633 ADD_TYPE(&PyIOBase_Type
, "_IOBase");
634 ADD_TYPE(&PyRawIOBase_Type
, "_RawIOBase");
635 ADD_TYPE(&PyBufferedIOBase_Type
, "_BufferedIOBase");
636 ADD_TYPE(&PyTextIOBase_Type
, "_TextIOBase");
638 /* Implementation of concrete IO objects. */
640 PyFileIO_Type
.tp_base
= &PyRawIOBase_Type
;
641 ADD_TYPE(&PyFileIO_Type
, "FileIO");
644 PyBytesIO_Type
.tp_base
= &PyBufferedIOBase_Type
;
645 ADD_TYPE(&PyBytesIO_Type
, "BytesIO");
648 PyStringIO_Type
.tp_base
= &PyTextIOBase_Type
;
649 ADD_TYPE(&PyStringIO_Type
, "StringIO");
652 PyBufferedReader_Type
.tp_base
= &PyBufferedIOBase_Type
;
653 ADD_TYPE(&PyBufferedReader_Type
, "BufferedReader");
656 PyBufferedWriter_Type
.tp_base
= &PyBufferedIOBase_Type
;
657 ADD_TYPE(&PyBufferedWriter_Type
, "BufferedWriter");
660 PyBufferedRWPair_Type
.tp_base
= &PyBufferedIOBase_Type
;
661 ADD_TYPE(&PyBufferedRWPair_Type
, "BufferedRWPair");
664 PyBufferedRandom_Type
.tp_base
= &PyBufferedIOBase_Type
;
665 ADD_TYPE(&PyBufferedRandom_Type
, "BufferedRandom");
668 PyTextIOWrapper_Type
.tp_base
= &PyTextIOBase_Type
;
669 ADD_TYPE(&PyTextIOWrapper_Type
, "TextIOWrapper");
671 /* IncrementalNewlineDecoder */
672 ADD_TYPE(&PyIncrementalNewlineDecoder_Type
, "IncrementalNewlineDecoder");
674 /* Interned strings */
675 if (!(_PyIO_str_close
= PyString_InternFromString("close")))
677 if (!(_PyIO_str_closed
= PyString_InternFromString("closed")))
679 if (!(_PyIO_str_decode
= PyString_InternFromString("decode")))
681 if (!(_PyIO_str_encode
= PyString_InternFromString("encode")))
683 if (!(_PyIO_str_fileno
= PyString_InternFromString("fileno")))
685 if (!(_PyIO_str_flush
= PyString_InternFromString("flush")))
687 if (!(_PyIO_str_getstate
= PyString_InternFromString("getstate")))
689 if (!(_PyIO_str_isatty
= PyString_InternFromString("isatty")))
691 if (!(_PyIO_str_newlines
= PyString_InternFromString("newlines")))
693 if (!(_PyIO_str_nl
= PyString_InternFromString("\n")))
695 if (!(_PyIO_str_read
= PyString_InternFromString("read")))
697 if (!(_PyIO_str_read1
= PyString_InternFromString("read1")))
699 if (!(_PyIO_str_readable
= PyString_InternFromString("readable")))
701 if (!(_PyIO_str_readinto
= PyString_InternFromString("readinto")))
703 if (!(_PyIO_str_readline
= PyString_InternFromString("readline")))
705 if (!(_PyIO_str_reset
= PyString_InternFromString("reset")))
707 if (!(_PyIO_str_seek
= PyString_InternFromString("seek")))
709 if (!(_PyIO_str_seekable
= PyString_InternFromString("seekable")))
711 if (!(_PyIO_str_setstate
= PyString_InternFromString("setstate")))
713 if (!(_PyIO_str_tell
= PyString_InternFromString("tell")))
715 if (!(_PyIO_str_truncate
= PyString_InternFromString("truncate")))
717 if (!(_PyIO_str_write
= PyString_InternFromString("write")))
719 if (!(_PyIO_str_writable
= PyString_InternFromString("writable")))
722 if (!(_PyIO_empty_str
= PyUnicode_FromStringAndSize(NULL
, 0)))
724 if (!(_PyIO_empty_bytes
= PyBytes_FromStringAndSize(NULL
, 0)))
726 if (!(_PyIO_zero
= PyLong_FromLong(0L)))
732 Py_CLEAR(_PyIO_os_module
);
733 Py_CLEAR(_PyIO_unsupported_operation
);