Logging to a file from a C-extension

Laura Creighton lac at openend.se
Wed Aug 19 10:13:35 CEST 2015


In a message of Tue, 18 Aug 2015 08:07:51 -0500, Al Pfalzgraf writes:
> If a logging file is opened at the level of a Python application, how would the log file name be communicated to a C-extension so that logging from the extension would be sent to the same log file?

To convert a file to an integer file descriptor, use PyFile_FromFd()

PyObject *fobj;     /* File object (already obtained somehow) */
int fd = PyObject_AsFileDescriptor(fobj);
if (fd < 0) {
   return NULL;
   }

This works for files, sockets, anything that produces a file descriptor.
Remember to flush your file on the Python side before you hand it to your
C extension, or your data will arrive scrambled, or you can lose some.

If you need to go the other way:

int fd;     /* Existing file descriptor (already open) */
PyObject *fobj = PyFile_FromFd(fd, "filename","r",-1,NULL,NULL,NULL,1);


More information about the Python-list mailing list