1
/* File object implementation (what's left of it -- see io.py) */
3
#define PY_SSIZE_T_CLEAN
6
#ifdef HAVE_GETC_UNLOCKED
7
#define GETC(f) getc_unlocked(f)
8
#define FLOCKFILE(f) flockfile(f)
9
#define FUNLOCKFILE(f) funlockfile(f)
11
#define GETC(f) getc(f)
13
#define FUNLOCKFILE(f)
17
#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
18
#define NEWLINE_CR 1 /* \r newline seen */
19
#define NEWLINE_LF 2 /* \n newline seen */
20
#define NEWLINE_CRLF 4 /* \r\n newline seen */
26
/* External C interface */
29
PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding,
30
char *errors, char *newline, int closefd)
32
PyObject *io, *stream, *nameobj = NULL;
34
io = PyImport_ImportModule("io");
37
stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode,
38
buffering, encoding, errors,
44
nameobj = PyUnicode_FromString(name);
48
if (PyObject_SetAttrString(stream, "name", nameobj) < 0)
57
PyFile_GetLine(PyObject *f, int n)
62
PyErr_BadInternalCall();
70
reader = PyObject_GetAttrString(f, "readline");
74
args = PyTuple_New(0);
76
args = Py_BuildValue("(i)", n);
81
result = PyEval_CallObject(reader, args);
84
if (result != NULL && !PyBytes_Check(result) &&
85
!PyUnicode_Check(result)) {
88
PyErr_SetString(PyExc_TypeError,
89
"object.readline() returned non-string");
93
if (n < 0 && result != NULL && PyBytes_Check(result)) {
94
char *s = PyBytes_AS_STRING(result);
95
Py_ssize_t len = PyBytes_GET_SIZE(result);
99
PyErr_SetString(PyExc_EOFError,
100
"EOF when reading a line");
102
else if (s[len-1] == '\n') {
103
if (result->ob_refcnt == 1)
104
_PyBytes_Resize(&result, len-1);
107
v = PyBytes_FromStringAndSize(s, len-1);
113
if (n < 0 && result != NULL && PyUnicode_Check(result)) {
114
Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
115
Py_ssize_t len = PyUnicode_GET_SIZE(result);
119
PyErr_SetString(PyExc_EOFError,
120
"EOF when reading a line");
122
else if (s[len-1] == '\n') {
123
if (result->ob_refcnt == 1)
124
PyUnicode_Resize(&result, len-1);
127
v = PyUnicode_FromUnicode(s, len-1);
136
/* Interfaces to write objects/strings to file-like objects */
139
PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
141
PyObject *writer, *value, *args, *result;
143
PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
146
writer = PyObject_GetAttrString(f, "write");
149
if (flags & Py_PRINT_RAW) {
150
value = PyObject_Str(v);
153
value = PyObject_Repr(v);
158
args = PyTuple_Pack(1, value);
164
result = PyEval_CallObject(writer, args);
175
PyFile_WriteString(const char *s, PyObject *f)
178
/* Should be caused by a pre-existing error */
179
if (!PyErr_Occurred())
180
PyErr_SetString(PyExc_SystemError,
181
"null file for PyFile_WriteString");
184
else if (!PyErr_Occurred()) {
185
PyObject *v = PyUnicode_FromString(s);
189
err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
197
/* Try to get a file-descriptor from a Python object. If the object
198
is an integer or long integer, its value is returned. If not, the
199
object's fileno() method is called if it exists; the method must return
200
an integer or long integer, which is returned as the file descriptor value.
201
-1 is returned on failure.
205
PyObject_AsFileDescriptor(PyObject *o)
210
if (PyLong_Check(o)) {
211
fd = PyLong_AsLong(o);
213
else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
215
PyObject *fno = PyEval_CallObject(meth, NULL);
220
if (PyLong_Check(fno)) {
221
fd = PyLong_AsLong(fno);
225
PyErr_SetString(PyExc_TypeError,
226
"fileno() returned a non-integer");
232
PyErr_SetString(PyExc_TypeError,
233
"argument must be an int, or have a fileno() method.");
237
if (fd == -1 && PyErr_Occurred())
240
PyErr_Format(PyExc_ValueError,
241
"file descriptor cannot be a negative integer (%i)",
249
** Py_UniversalNewlineFgets is an fgets variation that understands
250
** all of \r, \n and \r\n conventions.
251
** The stream should be opened in binary mode.
252
** If fobj is NULL the routine always does newline conversion, and
253
** it may peek one char ahead to gobble the second char in \r\n.
254
** If fobj is non-NULL it must be a PyFileObject. In this case there
255
** is no readahead but in stead a flag is used to skip a following
256
** \n on the next read. Also, if the file is open in binary mode
257
** the whole conversion is skipped. Finally, the routine keeps track of
258
** the different types of newlines seen.
259
** Note that we need no error handling: fgets() treats error and eof
263
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
267
int newlinetypes = 0;
271
errno = ENXIO; /* What can you do... */
275
c = 'x'; /* Shut up gcc warning */
276
while (--n > 0 && (c = GETC(stream)) != EOF ) {
280
/* Seeing a \n here with skipnextlf true
281
** means we saw a \r before.
283
newlinetypes |= NEWLINE_CRLF;
288
** Note that c == EOF also brings us here,
289
** so we're okay if the last char in the file
292
newlinetypes |= NEWLINE_CR;
296
/* A \r is translated into a \n, and we skip
297
** an adjacent \n, if any. We don't set the
298
** newlinetypes flag until we've seen the next char.
302
} else if ( c == '\n') {
303
newlinetypes |= NEWLINE_LF;
306
if (c == '\n') break;
308
if ( c == EOF && skipnextlf )
309
newlinetypes |= NEWLINE_CR;
313
/* If we have no file object we cannot save the
314
** skipnextlf flag. We have to readahead, which
315
** will cause a pause if we're reading from an
316
** interactive stream, but that is very unlikely
317
** unless we're doing something silly like
318
** exec(open("/dev/tty").read()).
329
/* **************************** std printer ****************************
330
* The stdprinter is used during the boot strapping phase as a preliminary
331
* file like object for sys.stderr.
337
} PyStdPrinter_Object;
340
stdprinter_new(PyTypeObject *type, PyObject *args, PyObject *kews)
342
PyStdPrinter_Object *self;
344
assert(type != NULL && type->tp_alloc != NULL);
346
self = (PyStdPrinter_Object *) type->tp_alloc(type, 0);
351
return (PyObject *) self;
355
fileio_init(PyObject *self, PyObject *args, PyObject *kwds)
357
PyErr_SetString(PyExc_TypeError,
358
"cannot create 'stderrprinter' instances");
363
PyFile_NewStdPrinter(int fd)
365
PyStdPrinter_Object *self;
367
if (fd != fileno(stdout) && fd != fileno(stderr)) {
368
/* not enough infrastructure for PyErr_BadInternalCall() */
372
self = PyObject_New(PyStdPrinter_Object,
377
return (PyObject*)self;
381
stdprinter_write(PyStdPrinter_Object *self, PyObject *args)
387
/* fd might be invalid on Windows
388
* I can't raise an exception here. It may lead to an
389
* unlimited recursion in the case stderr is invalid.
394
if (!PyArg_ParseTuple(args, "s", &c)) {
399
Py_BEGIN_ALLOW_THREADS
401
n = write(self->fd, c, n);
407
PyErr_SetFromErrno(PyExc_IOError);
411
return PyLong_FromSsize_t(n);
415
stdprinter_fileno(PyStdPrinter_Object *self)
417
return PyLong_FromLong((long) self->fd);
421
stdprinter_repr(PyStdPrinter_Object *self)
423
return PyUnicode_FromFormat("<stdprinter(fd=%d) object at 0x%x>",
428
stdprinter_noop(PyStdPrinter_Object *self)
434
stdprinter_isatty(PyStdPrinter_Object *self)
441
Py_BEGIN_ALLOW_THREADS
442
res = isatty(self->fd);
445
return PyBool_FromLong(res);
448
static PyMethodDef stdprinter_methods[] = {
449
{"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""},
450
{"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""},
451
{"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""},
452
{"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""},
453
{"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""},
454
{NULL, NULL} /*sentinel */
458
get_closed(PyStdPrinter_Object *self, void *closure)
465
get_mode(PyStdPrinter_Object *self, void *closure)
467
return PyUnicode_FromString("w");
471
get_encoding(PyStdPrinter_Object *self, void *closure)
476
static PyGetSetDef stdprinter_getsetlist[] = {
477
{"closed", (getter)get_closed, NULL, "True if the file is closed"},
478
{"encoding", (getter)get_encoding, NULL, "Encoding of the file"},
479
{"mode", (getter)get_mode, NULL, "String giving the file mode"},
483
PyTypeObject PyStdPrinter_Type = {
484
PyVarObject_HEAD_INIT(&PyType_Type, 0)
485
"stderrprinter", /* tp_name */
486
sizeof(PyStdPrinter_Object), /* tp_basicsize */
494
(reprfunc)stdprinter_repr, /* tp_repr */
495
0, /* tp_as_number */
496
0, /* tp_as_sequence */
497
0, /* tp_as_mapping */
501
PyObject_GenericGetAttr, /* tp_getattro */
503
0, /* tp_as_buffer */
504
Py_TPFLAGS_DEFAULT, /* tp_flags */
508
0, /* tp_richcompare */
509
0, /* tp_weaklistoffset */
512
stdprinter_methods, /* tp_methods */
514
stdprinter_getsetlist, /* tp_getset */
517
0, /* tp_descr_get */
518
0, /* tp_descr_set */
519
0, /* tp_dictoffset */
520
fileio_init, /* tp_init */
521
PyType_GenericAlloc, /* tp_alloc */
522
stdprinter_new, /* tp_new */
523
PyObject_Del, /* tp_free */