summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorAndrew M. Kuchling <amk@amk.ca>2000-07-13 23:56:54 (GMT)
committerAndrew M. Kuchling <amk@amk.ca>2000-07-13 23:56:54 (GMT)
commit06051edc0d4987994ccd9d578210a1fe1fa1d13a (patch)
tree6ca608758bb0d4d6d587cf0645ab0c77cb37ceb4 /Objects
parent9656abd913d359ecd48b07f4b4237b007f26d778 (diff)
downloadcpython-06051edc0d4987994ccd9d578210a1fe1fa1d13a.zip
cpython-06051edc0d4987994ccd9d578210a1fe1fa1d13a.tar.gz
cpython-06051edc0d4987994ccd9d578210a1fe1fa1d13a.tar.bz2
Added PyObject_AsFileDescriptor, which checks for integer, long integer,
or .fileno() method
Diffstat (limited to 'Objects')
-rw-r--r--Objects/fileobject.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/Objects/fileobject.c b/Objects/fileobject.c
index b02a56e..3458f8e 100644
--- a/Objects/fileobject.c
+++ b/Objects/fileobject.c
@@ -1098,3 +1098,61 @@ PyFile_WriteString(char *s, PyObject *f)
else
return -1;
}
+
+/* Try to get a file-descriptor from a Python object. If the object
+ is an integer or long integer, its value is returned. If not, the
+ object's fileno() method is called if it exists; the method must return
+ an integer or long integer, which is returned as the file descriptor value.
+ -1 is returned on failure.
+*/
+
+int PyObject_AsFileDescriptor(PyObject *o)
+{
+ int fd;
+ PyObject *meth;
+
+ if (PyInt_Check(o)) {
+ fd = PyInt_AsLong(o);
+ }
+ else if (PyLong_Check(o)) {
+ fd = PyLong_AsLong(o);
+ }
+ else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
+ {
+ PyObject *fno = PyEval_CallObject(meth, NULL);
+ Py_DECREF(meth);
+ if (fno == NULL)
+ return -1;
+
+ if (PyInt_Check(fno)) {
+ fd = PyInt_AsLong(fno);
+ Py_DECREF(fno);
+ }
+ else if (PyLong_Check(fno)) {
+ fd = PyLong_AsLong(fno);
+ Py_DECREF(fno);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "fileno() returned a non-integer");
+ Py_DECREF(fno);
+ return -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "argument must be an int, or have a fileno() method.");
+ return -1;
+ }
+
+ if (fd < 0) {
+ PyErr_Format(PyExc_ValueError,
+ "file descriptor cannot be a negative integer (%i)",
+ fd);
+ return -1;
+ }
+ return fd;
+}
+
+
+