2 /* File object implementation */
5 #include "structmember.h"
7 #ifndef DONT_HAVE_SYS_TYPES_H
9 #endif /* DONT_HAVE_SYS_TYPES_H */
11 /* We expect that fstat exists on most systems.
12 It's confirmed on Unix, Mac and Windows.
13 If you don't have it, add #define DONT_HAVE_FSTAT to your config.h. */
14 #ifndef DONT_HAVE_FSTAT
17 #ifndef DONT_HAVE_SYS_TYPES_H
18 #include <sys/types.h>
21 #ifndef DONT_HAVE_SYS_STAT_H
29 #endif /* DONT_HAVE_FSTAT */
36 #define fileno _fileno
37 /* can (almost fully) duplicate with _chsize, see file_truncate */
38 #define HAVE_FTRUNCATE
43 #define HAVE_FTRUNCATE
48 /* Mwerks fopen() doesn't always set errno */
49 #define NO_FOPEN_ERRNO
52 #define BUF(v) PyString_AS_STRING((PyStringObject *)v)
54 #ifndef DONT_HAVE_ERRNO_H
58 /* define the appropriate 64-bit capable tell() function */
60 #define TELL64 _telli64
61 #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(_HAVE_BSDI) || defined(__APPLE__)
62 /* NOTE: this is only used on older
63 NetBSD prior to f*o() funcions */
64 #define TELL64(fd) lseek((fd),0,SEEK_CUR)
73 int (*f_close
)(FILE *);
74 int f_softspace
; /* Flag used by 'print' command */
75 int f_binary
; /* Flag which indicates whether the file is open
76 open in binary (1) or test (0) mode */
80 PyFile_AsFile(PyObject
*f
)
82 if (f
== NULL
|| !PyFile_Check(f
))
85 return ((PyFileObject
*)f
)->f_fp
;
89 PyFile_Name(PyObject
*f
)
91 if (f
== NULL
|| !PyFile_Check(f
))
94 return ((PyFileObject
*)f
)->f_name
;
98 PyFile_FromFile(FILE *fp
, char *name
, char *mode
, int (*close
)(FILE *))
100 PyFileObject
*f
= PyObject_NEW(PyFileObject
, &PyFile_Type
);
104 f
->f_name
= PyString_FromString(name
);
105 f
->f_mode
= PyString_FromString(mode
);
108 if (strchr(mode
,'b') != NULL
)
112 if (f
->f_name
== NULL
|| f
->f_mode
== NULL
) {
117 return (PyObject
*) f
;
121 PyFile_FromString(char *name
, char *mode
)
123 extern int fclose(FILE *);
125 f
= (PyFileObject
*) PyFile_FromFile((FILE *)NULL
, name
, mode
, fclose
);
131 f
->f_fp
= fopenRF(name
, mode
+1);
136 Py_BEGIN_ALLOW_THREADS
137 f
->f_fp
= fopen(name
, mode
);
140 if (f
->f_fp
== NULL
) {
141 #ifdef NO_FOPEN_ERRNO
142 /* Metroworks only, not testable, so unchanged */
144 PyErr_SetString(PyExc_IOError
, "Cannot open file");
149 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, name
);
153 return (PyObject
*)f
;
157 PyFile_SetBufSize(PyObject
*f
, int bufsize
)
173 setvbuf(((PyFileObject
*)f
)->f_fp
, (char *)NULL
,
175 #else /* !HAVE_SETVBUF */
177 setbuf(((PyFileObject
*)f
)->f_fp
, (char *)NULL
);
178 #endif /* !HAVE_SETVBUF */
185 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
192 file_dealloc(PyFileObject
*f
)
194 if (f
->f_fp
!= NULL
&& f
->f_close
!= NULL
) {
195 Py_BEGIN_ALLOW_THREADS
196 (*f
->f_close
)(f
->f_fp
);
199 if (f
->f_name
!= NULL
) {
200 Py_DECREF(f
->f_name
);
202 if (f
->f_mode
!= NULL
) {
203 Py_DECREF(f
->f_mode
);
209 file_repr(PyFileObject
*f
)
212 sprintf(buf
, "<%s file '%.256s', mode '%.10s' at %p>",
213 f
->f_fp
== NULL
? "closed" : "open",
214 PyString_AsString(f
->f_name
),
215 PyString_AsString(f
->f_mode
),
217 return PyString_FromString(buf
);
221 file_close(PyFileObject
*f
, PyObject
*args
)
224 if (!PyArg_NoArgs(args
))
226 if (f
->f_fp
!= NULL
) {
227 if (f
->f_close
!= NULL
) {
228 Py_BEGIN_ALLOW_THREADS
230 sts
= (*f
->f_close
)(f
->f_fp
);
236 return PyErr_SetFromErrno(PyExc_IOError
);
238 return PyInt_FromLong((long)sts
);
244 /* a portable fseek() function
245 return 0 on success, non-zero on failure (with errno set) */
247 #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8
248 _portable_fseek(FILE *fp
, fpos_t offset
, int whence
)
250 _portable_fseek(FILE *fp
, off_t offset
, int whence
)
253 #if defined(HAVE_FSEEKO)
254 return fseeko(fp
, offset
, whence
);
255 #elif defined(HAVE_FSEEK64)
256 return fseek64(fp
, offset
, whence
);
257 #elif defined(__BEOS__)
258 return _fseek(fp
, offset
, whence
);
259 #elif defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_FPOS_T >= 8
260 /* lacking a 64-bit capable fseek() (as Win64 does) use a 64-bit capable
261 fsetpos() and tell() to implement fseek()*/
265 if (fgetpos(fp
, &pos
) != 0)
270 /* do a "no-op" seek first to sync the buffering so that
271 the low-level tell() can be used correctly */
272 if (fseek(fp
, 0, SEEK_END
) != 0)
274 if ((pos
= TELL64(fileno(fp
))) == -1L)
278 /* case SEEK_SET: break; */
280 return fsetpos(fp
, &offset
);
282 return fseek(fp
, offset
, whence
);
287 /* a portable ftell() function
288 Return -1 on failure with errno set appropriately, current file
289 position on success */
290 #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8
295 _portable_ftell(FILE* fp
)
297 #if defined(HAVE_FTELLO) && defined(HAVE_LARGEFILE_SUPPORT)
299 #elif defined(HAVE_FTELL64) && defined(HAVE_LARGEFILE_SUPPORT)
301 #elif SIZEOF_FPOS_T >= 8 && defined(HAVE_LARGEFILE_SUPPORT)
303 if (fgetpos(fp
, &pos
) != 0)
313 file_seek(PyFileObject
*f
, PyObject
*args
)
317 #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8
321 #endif /* !MS_WIN64 */
327 if (!PyArg_ParseTuple(args
, "O|i:seek", &offobj
, &whence
))
329 #if !defined(HAVE_LARGEFILE_SUPPORT)
330 offset
= PyInt_AsLong(offobj
);
332 offset
= PyLong_Check(offobj
) ?
333 PyLong_AsLongLong(offobj
) : PyInt_AsLong(offobj
);
335 if (PyErr_Occurred())
338 Py_BEGIN_ALLOW_THREADS
340 ret
= _portable_fseek(f
->f_fp
, offset
, whence
);
344 PyErr_SetFromErrno(PyExc_IOError
);
353 #ifdef HAVE_FTRUNCATE
355 file_truncate(PyFileObject
*f
, PyObject
*args
)
358 #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8
363 PyObject
*newsizeobj
;
368 if (!PyArg_ParseTuple(args
, "|O:truncate", &newsizeobj
))
370 if (newsizeobj
!= NULL
) {
371 #if !defined(HAVE_LARGEFILE_SUPPORT)
372 newsize
= PyInt_AsLong(newsizeobj
);
374 newsize
= PyLong_Check(newsizeobj
) ?
375 PyLong_AsLongLong(newsizeobj
) :
376 PyInt_AsLong(newsizeobj
);
378 if (PyErr_Occurred())
381 /* Default to current position*/
382 Py_BEGIN_ALLOW_THREADS
384 newsize
= _portable_ftell(f
->f_fp
);
387 PyErr_SetFromErrno(PyExc_IOError
);
392 Py_BEGIN_ALLOW_THREADS
394 ret
= fflush(f
->f_fp
);
396 if (ret
!= 0) goto onioerror
;
399 /* can use _chsize; if, however, the newsize overflows 32-bits then
400 _chsize is *not* adequate; in this case, an OverflowError is raised */
401 if (newsize
> LONG_MAX
) {
402 PyErr_SetString(PyExc_OverflowError
,
403 "the new size is too long for _chsize (it is limited to 32-bit values)");
406 Py_BEGIN_ALLOW_THREADS
408 ret
= _chsize(fileno(f
->f_fp
), newsize
);
410 if (ret
!= 0) goto onioerror
;
413 Py_BEGIN_ALLOW_THREADS
415 ret
= ftruncate(fileno(f
->f_fp
), newsize
);
417 if (ret
!= 0) goto onioerror
;
418 #endif /* !MS_WIN32 */
424 PyErr_SetFromErrno(PyExc_IOError
);
428 #endif /* HAVE_FTRUNCATE */
431 file_tell(PyFileObject
*f
, PyObject
*args
)
433 #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8
441 if (!PyArg_NoArgs(args
))
443 Py_BEGIN_ALLOW_THREADS
445 pos
= _portable_ftell(f
->f_fp
);
448 PyErr_SetFromErrno(PyExc_IOError
);
452 #if !defined(HAVE_LARGEFILE_SUPPORT)
453 return PyInt_FromLong(pos
);
455 return PyLong_FromLongLong(pos
);
460 file_fileno(PyFileObject
*f
, PyObject
*args
)
464 if (!PyArg_NoArgs(args
))
466 return PyInt_FromLong((long) fileno(f
->f_fp
));
470 file_flush(PyFileObject
*f
, PyObject
*args
)
476 if (!PyArg_NoArgs(args
))
478 Py_BEGIN_ALLOW_THREADS
480 res
= fflush(f
->f_fp
);
483 PyErr_SetFromErrno(PyExc_IOError
);
492 file_isatty(PyFileObject
*f
, PyObject
*args
)
497 if (!PyArg_NoArgs(args
))
499 Py_BEGIN_ALLOW_THREADS
500 res
= isatty((int)fileno(f
->f_fp
));
502 return PyInt_FromLong(res
);
507 #define SMALLCHUNK 8192
509 #define SMALLCHUNK BUFSIZ
513 #define BIGCHUNK (512 * 32)
515 #define BIGCHUNK (512 * 1024)
519 new_buffersize(PyFileObject
*f
, size_t currentsize
)
524 if (fstat(fileno(f
->f_fp
), &st
) == 0) {
526 /* The following is not a bug: we really need to call lseek()
527 *and* ftell(). The reason is that some stdio libraries
528 mistakenly flush their buffer when ftell() is called and
529 the lseek() call it makes fails, thereby throwing away
530 data that cannot be recovered in any way. To avoid this,
531 we first test lseek(), and only call ftell() if lseek()
532 works. We can't use the lseek() value either, because we
533 need to take the amount of buffered data into account.
534 (Yet another reason why stdio stinks. :-) */
535 pos
= lseek(fileno(f
->f_fp
), 0L, SEEK_CUR
);
537 pos
= ftell(f
->f_fp
);
540 if (end
> pos
&& pos
>= 0)
541 return currentsize
+ end
- pos
+ 1;
542 /* Add 1 so if the file were to grow we'd notice. */
545 if (currentsize
> SMALLCHUNK
) {
546 /* Keep doubling until we reach BIGCHUNK;
547 then keep adding BIGCHUNK. */
548 if (currentsize
<= BIGCHUNK
)
549 return currentsize
+ currentsize
;
551 return currentsize
+ BIGCHUNK
;
553 return currentsize
+ SMALLCHUNK
;
557 file_read(PyFileObject
*f
, PyObject
*args
)
559 long bytesrequested
= -1;
560 size_t bytesread
, buffersize
, chunksize
;
565 if (!PyArg_ParseTuple(args
, "|l:read", &bytesrequested
))
567 if (bytesrequested
< 0)
568 buffersize
= new_buffersize(f
, (size_t)0);
570 buffersize
= bytesrequested
;
571 if (buffersize
> INT_MAX
) {
572 PyErr_SetString(PyExc_OverflowError
,
573 "requested number of bytes is more than a Python string can hold");
576 v
= PyString_FromStringAndSize((char *)NULL
, buffersize
);
581 Py_BEGIN_ALLOW_THREADS
583 chunksize
= fread(BUF(v
) + bytesread
, 1,
584 buffersize
- bytesread
, f
->f_fp
);
586 if (chunksize
== 0) {
587 if (!ferror(f
->f_fp
))
589 PyErr_SetFromErrno(PyExc_IOError
);
594 bytesread
+= chunksize
;
595 if (bytesread
< buffersize
)
597 if (bytesrequested
< 0) {
598 buffersize
= new_buffersize(f
, buffersize
);
599 if (_PyString_Resize(&v
, buffersize
) < 0)
603 if (bytesread
!= buffersize
)
604 _PyString_Resize(&v
, bytesread
);
609 file_readinto(PyFileObject
*f
, PyObject
*args
)
612 size_t ntodo
, ndone
, nnow
;
616 if (!PyArg_Parse(args
, "w#", &ptr
, &ntodo
))
620 Py_BEGIN_ALLOW_THREADS
622 nnow
= fread(ptr
+ndone
, 1, ntodo
, f
->f_fp
);
625 if (!ferror(f
->f_fp
))
627 PyErr_SetFromErrno(PyExc_IOError
);
634 return PyInt_FromLong((long)ndone
);
638 /* Internal routine to get a line.
639 Size argument interpretation:
641 = 0: read arbitrary line;
642 < 0: strip trailing '\n', raise EOFError if EOF reached immediately
646 get_line(PyFileObject
*f
, int n
)
648 register FILE *fp
= f
->f_fp
;
654 #if defined(HAVE_GETLINE) && defined(_GNU_SOURCE)
655 /* Use GNU libc extension getline() for arbitrary-sized lines */
659 Py_BEGIN_ALLOW_THREADS
660 n1
= getline(&buf
, &size
, fp
);
667 if (PyErr_CheckSignals()) {
670 if (n
< 0 && feof(fp
)) {
671 PyErr_SetString(PyExc_EOFError
,
672 "EOF when reading a line");
675 return PyString_FromStringAndSize(NULL
, 0);
679 v
= PyString_FromStringAndSize(buf
, n1
);
685 n2
= n
> 0 ? n
: 100;
686 v
= PyString_FromStringAndSize((char *)NULL
, n2
);
692 Py_BEGIN_ALLOW_THREADS
694 if ((c
= getc(fp
)) == EOF
) {
697 if (PyErr_CheckSignals()) {
701 if (n
< 0 && buf
== BUF(v
)) {
703 PyErr_SetString(PyExc_EOFError
,
704 "EOF when reading a line");
710 if ((*buf
++ = c
) == '\n') {
721 PyErr_SetString(PyExc_OverflowError
,
722 "line is longer than a Python string can hold");
726 if (_PyString_Resize(&v
, n2
) < 0)
737 _PyString_Resize(&v
, n1
);
741 /* External C interface */
744 PyFile_GetLine(PyObject
*f
, int n
)
747 PyErr_BadInternalCall();
750 if (!PyFile_Check(f
)) {
754 reader
= PyObject_GetAttrString(f
, "readline");
758 args
= Py_BuildValue("()");
760 args
= Py_BuildValue("(i)", n
);
765 result
= PyEval_CallObject(reader
, args
);
768 if (result
!= NULL
&& !PyString_Check(result
)) {
771 PyErr_SetString(PyExc_TypeError
,
772 "object.readline() returned non-string");
774 if (n
< 0 && result
!= NULL
) {
775 char *s
= PyString_AsString(result
);
776 int len
= PyString_Size(result
);
780 PyErr_SetString(PyExc_EOFError
,
781 "EOF when reading a line");
783 else if (s
[len
-1] == '\n') {
784 if (result
->ob_refcnt
== 1)
785 _PyString_Resize(&result
, len
-1);
788 v
= PyString_FromStringAndSize(s
,
797 if (((PyFileObject
*)f
)->f_fp
== NULL
)
799 return get_line((PyFileObject
*)f
, n
);
805 file_readline(PyFileObject
*f
, PyObject
*args
)
811 if (!PyArg_ParseTuple(args
, "|i:readline", &n
))
814 return PyString_FromString("");
817 return get_line(f
, n
);
821 file_readlines(PyFileObject
*f
, PyObject
*args
)
826 char small_buffer
[SMALLCHUNK
];
827 char *buffer
= small_buffer
;
828 size_t buffersize
= SMALLCHUNK
;
829 PyObject
*big_buffer
= NULL
;
832 size_t totalread
= 0;
838 if (!PyArg_ParseTuple(args
, "|l:readlines", &sizehint
))
840 if ((list
= PyList_New(0)) == NULL
)
843 Py_BEGIN_ALLOW_THREADS
845 nread
= fread(buffer
+nfilled
, 1, buffersize
-nfilled
, f
->f_fp
);
849 if (!ferror(f
->f_fp
))
851 PyErr_SetFromErrno(PyExc_IOError
);
859 p
= memchr(buffer
+nfilled
, '\n', nread
);
861 /* Need a larger buffer to fit this line */
864 if (buffersize
> INT_MAX
) {
865 PyErr_SetString(PyExc_OverflowError
,
866 "line is longer than a Python string can hold");
869 if (big_buffer
== NULL
) {
870 /* Create the big buffer */
871 big_buffer
= PyString_FromStringAndSize(
873 if (big_buffer
== NULL
)
875 buffer
= PyString_AS_STRING(big_buffer
);
876 memcpy(buffer
, small_buffer
, nfilled
);
879 /* Grow the big buffer */
880 _PyString_Resize(&big_buffer
, buffersize
);
881 buffer
= PyString_AS_STRING(big_buffer
);
885 end
= buffer
+nfilled
+nread
;
888 /* Process complete lines */
890 line
= PyString_FromStringAndSize(q
, p
-q
);
893 err
= PyList_Append(list
, line
);
898 p
= memchr(q
, '\n', end
-q
);
900 /* Move the remaining incomplete line to the start */
902 memmove(buffer
, q
, nfilled
);
904 if (totalread
>= (size_t)sizehint
)
908 /* Partial last line */
909 line
= PyString_FromStringAndSize(buffer
, nfilled
);
913 /* Need to complete the last line */
914 PyObject
*rest
= get_line(f
, 0);
919 PyString_Concat(&line
, rest
);
924 err
= PyList_Append(list
, line
);
931 Py_DECREF(big_buffer
);
937 file_write(PyFileObject
*f
, PyObject
*args
)
943 if (!PyArg_Parse(args
, f
->f_binary
? "s#" : "t#", &s
, &n
))
946 Py_BEGIN_ALLOW_THREADS
948 n2
= fwrite(s
, 1, n
, f
->f_fp
);
951 PyErr_SetFromErrno(PyExc_IOError
);
960 file_writelines(PyFileObject
*f
, PyObject
*args
)
962 #define CHUNKSIZE 1000
963 PyObject
*list
, *line
;
965 int i
, j
, index
, len
, nwritten
, islist
;
969 if (args
== NULL
|| !PySequence_Check(args
)) {
970 PyErr_SetString(PyExc_TypeError
,
971 "writelines() argument must be a sequence of strings");
974 islist
= PyList_Check(args
);
976 /* Strategy: slurp CHUNKSIZE lines into a private list,
977 checking that they are all strings, then write that list
978 without holding the interpreter lock, then come back for more. */
983 list
= PyList_New(CHUNKSIZE
);
992 list
= PyList_GetSlice(args
, index
, index
+CHUNKSIZE
);
995 j
= PyList_GET_SIZE(list
);
998 for (j
= 0; j
< CHUNKSIZE
; j
++) {
999 line
= PySequence_GetItem(args
, index
+j
);
1001 if (PyErr_ExceptionMatches(
1002 PyExc_IndexError
)) {
1006 /* Some other error occurred.
1007 XXX We may lose some output. */
1010 PyList_SetItem(list
, j
, line
);
1016 /* Check that all entries are indeed strings. If not,
1017 apply the same rules as for file.write() and
1018 convert the results to strings. This is slow, but
1019 seems to be the only way since all conversion APIs
1020 could potentially execute Python code. */
1021 for (i
= 0; i
< j
; i
++) {
1022 PyObject
*v
= PyList_GET_ITEM(list
, i
);
1023 if (!PyString_Check(v
)) {
1026 if (((f
->f_binary
&&
1027 PyObject_AsReadBuffer(v
,
1028 (const void**)&buffer
,
1030 PyObject_AsCharBuffer(v
,
1033 PyErr_SetString(PyExc_TypeError
,
1034 "writelines() argument must be a sequence of strings");
1037 line
= PyString_FromStringAndSize(buffer
,
1042 PyList_SET_ITEM(list
, i
, line
);
1046 /* Since we are releasing the global lock, the
1047 following code may *not* execute Python code. */
1048 Py_BEGIN_ALLOW_THREADS
1051 for (i
= 0; i
< j
; i
++) {
1052 line
= PyList_GET_ITEM(list
, i
);
1053 len
= PyString_GET_SIZE(line
);
1054 nwritten
= fwrite(PyString_AS_STRING(line
),
1056 if (nwritten
!= len
) {
1058 PyErr_SetFromErrno(PyExc_IOError
);
1063 Py_END_ALLOW_THREADS
1077 static PyMethodDef file_methods
[] = {
1078 {"readline", (PyCFunction
)file_readline
, 1},
1079 {"read", (PyCFunction
)file_read
, 1},
1080 {"write", (PyCFunction
)file_write
, 0},
1081 {"fileno", (PyCFunction
)file_fileno
, 0},
1082 {"seek", (PyCFunction
)file_seek
, 1},
1083 #ifdef HAVE_FTRUNCATE
1084 {"truncate", (PyCFunction
)file_truncate
, 1},
1086 {"tell", (PyCFunction
)file_tell
, 0},
1087 {"readinto", (PyCFunction
)file_readinto
, 0},
1088 {"readlines", (PyCFunction
)file_readlines
, 1},
1089 {"writelines", (PyCFunction
)file_writelines
, 0},
1090 {"flush", (PyCFunction
)file_flush
, 0},
1091 {"close", (PyCFunction
)file_close
, 0},
1092 {"isatty", (PyCFunction
)file_isatty
, 0},
1093 {NULL
, NULL
} /* sentinel */
1096 #define OFF(x) offsetof(PyFileObject, x)
1098 static struct memberlist file_memberlist
[] = {
1099 {"softspace", T_INT
, OFF(f_softspace
)},
1100 {"mode", T_OBJECT
, OFF(f_mode
), RO
},
1101 {"name", T_OBJECT
, OFF(f_name
), RO
},
1102 /* getattr(f, "closed") is implemented without this table */
1103 {"closed", T_INT
, 0, RO
},
1104 {NULL
} /* Sentinel */
1108 file_getattr(PyFileObject
*f
, char *name
)
1112 res
= Py_FindMethod(file_methods
, (PyObject
*)f
, name
);
1116 if (strcmp(name
, "closed") == 0)
1117 return PyInt_FromLong((long)(f
->f_fp
== 0));
1118 return PyMember_Get((char *)f
, file_memberlist
, name
);
1122 file_setattr(PyFileObject
*f
, char *name
, PyObject
*v
)
1125 PyErr_SetString(PyExc_AttributeError
,
1126 "can't delete file attributes");
1129 return PyMember_Set((char *)f
, file_memberlist
, name
, v
);
1132 PyTypeObject PyFile_Type
= {
1133 PyObject_HEAD_INIT(&PyType_Type
)
1136 sizeof(PyFileObject
),
1138 (destructor
)file_dealloc
, /*tp_dealloc*/
1140 (getattrfunc
)file_getattr
, /*tp_getattr*/
1141 (setattrfunc
)file_setattr
, /*tp_setattr*/
1143 (reprfunc
)file_repr
, /*tp_repr*/
1146 /* Interface for the 'soft space' between print items. */
1149 PyFile_SoftSpace(PyObject
*f
, int newflag
)
1155 else if (PyFile_Check(f
)) {
1156 oldflag
= ((PyFileObject
*)f
)->f_softspace
;
1157 ((PyFileObject
*)f
)->f_softspace
= newflag
;
1161 v
= PyObject_GetAttrString(f
, "softspace");
1166 oldflag
= PyInt_AsLong(v
);
1169 v
= PyInt_FromLong((long)newflag
);
1173 if (PyObject_SetAttrString(f
, "softspace", v
) != 0)
1181 /* Interfaces to write objects/strings to file-like objects */
1184 PyFile_WriteObject(PyObject
*v
, PyObject
*f
, int flags
)
1186 PyObject
*writer
, *value
, *args
, *result
;
1188 PyErr_SetString(PyExc_TypeError
, "writeobject with NULL file");
1191 else if (PyFile_Check(f
)) {
1192 FILE *fp
= PyFile_AsFile(f
);
1197 return PyObject_Print(v
, fp
, flags
);
1199 writer
= PyObject_GetAttrString(f
, "write");
1202 if (flags
& Py_PRINT_RAW
)
1203 value
= PyObject_Str(v
);
1205 value
= PyObject_Repr(v
);
1206 if (value
== NULL
) {
1210 args
= Py_BuildValue("(O)", value
);
1216 result
= PyEval_CallObject(writer
, args
);
1227 PyFile_WriteString(char *s
, PyObject
*f
)
1230 /* Should be caused by a pre-existing error */
1231 if (!PyErr_Occurred())
1232 PyErr_SetString(PyExc_SystemError
,
1233 "null file for PyFile_WriteString");
1236 else if (PyFile_Check(f
)) {
1237 FILE *fp
= PyFile_AsFile(f
);
1245 else if (!PyErr_Occurred()) {
1246 PyObject
*v
= PyString_FromString(s
);
1250 err
= PyFile_WriteObject(v
, f
, Py_PRINT_RAW
);
1258 /* Try to get a file-descriptor from a Python object. If the object
1259 is an integer or long integer, its value is returned. If not, the
1260 object's fileno() method is called if it exists; the method must return
1261 an integer or long integer, which is returned as the file descriptor value.
1262 -1 is returned on failure.
1265 int PyObject_AsFileDescriptor(PyObject
*o
)
1270 if (PyInt_Check(o
)) {
1271 fd
= PyInt_AsLong(o
);
1273 else if (PyLong_Check(o
)) {
1274 fd
= PyLong_AsLong(o
);
1276 else if ((meth
= PyObject_GetAttrString(o
, "fileno")) != NULL
)
1278 PyObject
*fno
= PyEval_CallObject(meth
, NULL
);
1283 if (PyInt_Check(fno
)) {
1284 fd
= PyInt_AsLong(fno
);
1287 else if (PyLong_Check(fno
)) {
1288 fd
= PyLong_AsLong(fno
);
1292 PyErr_SetString(PyExc_TypeError
,
1293 "fileno() returned a non-integer");
1299 PyErr_SetString(PyExc_TypeError
,
1300 "argument must be an int, or have a fileno() method.");
1305 PyErr_Format(PyExc_ValueError
,
1306 "file descriptor cannot be a negative integer (%i)",