12. File Paths and Files¶
This chapter describes reading and writing files from CPython C extensions.
12.1. File Paths¶
There are several builtin functions that allow conversion between Python and C described in the File System Encoding API which uses the filesystem encoding and error handler, see also File Objects
In summary:
PyUnicode_FSConverter() Converts a Python a
stror path-like object to a Pythonbytesobject.PyUnicode_FSDecoder() Converts a Python
bytesobject to a Pythonstr.PyUnicode_DecodeFSDefaultAndSize() Takes a C string and length and returns a Python
str.PyUnicode_DecodeFSDefault() Takes a null terminated C string and length and returns a Python
str.PyUnicode_EncodeFSDefault() Takes a Python
strand return a Pythonbytesobject.
The example code is in:
src/cpy/cFile.cppsrc/cpy/PythonFileWrapper.hsrc/cpy/PythonFileWrapper.cpp
The Python tests are in tests/unit/test_c_file.py.
12.1.1. Parsing File Paths as Arguments¶
The Python API provides functionality for converting Python file paths (a str or path-like object)
to C file paths (char *).
From Python to C; PyUnicode_FSConverter()
and the reverse from C to Python PyUnicode_DecodeFSDefaultAndSize()
Here is an example of taking a Python Unicode string representing a file path, converting it to C and then back to Python. The stages are:
Use PyArg_ParseTupleAndKeywords() and PyUnicode_FSConverter() to convert the path-like Python object to a Python
bytesobject. Note the use of the"O&"formatting string that takes a Python object and a conversion function.Extract the raws bytes to use as a C path.
Take a C path and convert it to a Python Unicode
strand return it.
The Python signature is:
def parse_filesystem_argument(path: typing.Union[str, pathlib.Path]) -> str:
Here is the C code:
1static PyObject *
2parse_filesystem_argument(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwargs) {
3 assert(!PyErr_Occurred());
4 assert(args || kwargs);
5
6 PyBytesObject *py_path = NULL;
7 char *c_path = NULL;
8 Py_ssize_t path_size;
9 PyObject *ret = NULL;
10
11 /* Parse arguments */
12 static char *kwlist[] = {"path", NULL};
13 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&", kwlist, PyUnicode_FSConverter,
14 &py_path)) {
15 goto except;
16 }
17 /* Check arguments. */
18 assert(py_path);
19 /* Grab a reference to the internal bytes buffer. */
20 if (PyBytes_AsStringAndSize((PyObject *) py_path, &c_path, &path_size)) {
21 /* Should have a TypeError or ValueError. */
22 assert(PyErr_Occurred());
23 assert(PyErr_ExceptionMatches(PyExc_TypeError)
24 || PyErr_ExceptionMatches(PyExc_ValueError));
25 goto except;
26 }
27 assert(c_path);
28 /* Use the C path. */
29
30 /* Now convert the C path to a Python object, a string. */
31 ret = PyUnicode_DecodeFSDefaultAndSize(c_path, path_size);
32 if (!ret) {
33 goto except;
34 }
35 assert(!PyErr_Occurred());
36 goto finally;
37except:
38 assert(PyErr_Occurred());
39 Py_XDECREF(ret);
40 ret = NULL;
41finally:
42 // Decref temporary locals.
43 Py_XDECREF(py_path);
44 return ret;
45}
12.2. Files¶
This section describes how to interoperate between Python files, C FILE* and C++ iostream objects.
12.2.1. Reading a Python File¶
Here is an example of reading from a Python file in C. The Python signature is:
def read_python_file_to_c(file_object: typing.IO, size: int = -1) -> bytes:
The technique is to get the read() method from the file object with PyObject_GetAttrString then call it with the
appropriate arguments using PyObject_Call.
Here is the C code:
1static PyObject *
2read_python_file_to_c(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
3 assert(!PyErr_Occurred());
4 static const char *kwlist[] = {"file_object", "size", NULL};
5 PyObject *py_file_object = NULL;
6 Py_ssize_t bytes_to_read = -1;
7 PyObject *py_read_meth = NULL;
8 PyObject *py_read_args = NULL;
9 PyObject *py_read_data = NULL;
10 char *c_bytes_data = NULL;
11 PyObject *ret = NULL;
12
13 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n", (char **) (kwlist),
14 &py_file_object, &bytes_to_read)) {
15 return NULL;
16 }
17 // Check that this is a readable file, well does it have a read method?
18 /* Get the read method of the passed object */
19 py_read_meth = PyObject_GetAttrString(py_file_object, "read"); // New reference
20 if (py_read_meth == NULL) {
21 PyErr_Format(PyExc_ValueError,
22 "Argument of type %s does not have a read() method.",
23 Py_TYPE(py_file_object)->tp_name);
24 goto except;
25 }
26 if (!PyCallable_Check(py_read_meth)) {
27 PyErr_Format(PyExc_ValueError,
28 "read attribute of type %s is not callable.",
29 Py_TYPE(py_file_object)->tp_name);
30 goto except;
31 }
32 // Call read(VisibleRecord::NUMBER_OF_HEADER_BYTES) to get a Python bytes object.
33 py_read_args = Py_BuildValue("(i)", bytes_to_read);
34 if (!py_read_args) {
35 goto except;
36 }
37 // This should advance that readable file pointer.
38 py_read_data = PyObject_Call(py_read_meth, py_read_args, NULL);
39 if (py_read_data == NULL) {
40 goto except;
41 }
42 /* Check for EOF */
43 if (bytes_to_read >= 0 && PySequence_Length(py_read_data) != bytes_to_read) {
44 assert(PyErr_Occurred());
45 PyErr_Format(PyExc_IOError,
46 "Reading file object gives EOF. Requested bytes %ld, got %ld.",
47 bytes_to_read, PySequence_Length(py_read_data));
48 goto except;
49 }
50 c_bytes_data = PyBytes_AsString(py_read_data);
51 if (c_bytes_data == NULL) {
52 // TypeError already set.
53 goto except;
54 }
55 ret = py_read_data;
56 goto finally;
57except:
58 /* Handle every abnormal condition and clean up. */
59 assert(PyErr_Occurred());
60 ret = NULL;
61finally:
62 /* Clean up under normal conditions and return an appropriate value. */
63 Py_XDECREF(py_read_meth);
64 Py_XDECREF(py_read_args);
65 return ret;
66}
12.2.2. Writing to a Python File¶
A similar technique can be used to write to a file, however there are a couple of C functions for writing directly to a Python file:
12.2.2.1. PyFile_WriteObject()¶
This writes a Python object to a Python file using the objects __str__ method
(if Py_PRINT_RAW is given as the flags argument or
the objects __repr__ method if flags is zero.
12.2.2.2. PyFile_WriteString()¶
This will write a C char * to a Python file.
Note
PyFile_WriteString() creates a unicode string and then calls PyFile_WriteObject()
so the Python file object must be capable of writing strings.
Here is an example of taking a Python bytes object, extracting the char * C buffer and writing that to a Python
file.
The Python function signature is:
def write_bytes_to_python_file(bytes_to_write: bytes, file_object: typing.IO) -> int:
Here is the C code:
1static PyObject *
2write_bytes_to_python_file(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
3 assert(!PyErr_Occurred());
4 static const char *kwlist[] = {"bytes_to_write", "file_object", NULL};
5 PyObject *py_file_object = NULL;
6 Py_buffer c_buffer;
7 PyObject *ret = NULL;
8
9 if (!PyArg_ParseTupleAndKeywords(args, kwds, "y*O", (char **) (kwlist),
10 &c_buffer, &py_file_object)) {
11 return NULL;
12 }
13 /* NOTE: PyFile_WriteString() creates a unicode string and then
14 * calls PyFile_WriteObject() so the py_file_object must be
15 * capable of writing strings. */
16 int result = PyFile_WriteString((char *)c_buffer.buf, py_file_object);
17 if (result != 0) {
18 goto except;
19 }
20 ret = Py_BuildValue("n", c_buffer.len);
21 goto finally;
22except:
23 assert(PyErr_Occurred());
24 ret = NULL;
25finally:
26 return ret;
27}
12.2.2.3. A C++ Python File Wrapper¶
In src/cpy/PythonFileWrapper.h and src/cpy/PythonFileWrapper.cpp there is a C++ class that takes a Python file
and extracts the read(), write(), seek() and tell() methods that can then be used to read and write to
the Python file from C++.
Here is the class:
1/// Class that is created with a PyObject* that looks like a Python File.
2/// This can then read from that file object ans write to a user provided C++ stream or read from a user provided C++
3/// stream and write to the give Python file like object.
4class PythonFileObjectWrapper {
5public:
6 explicit PythonFileObjectWrapper(PyObject *python_file_object);
7
8 /// Read from a Python file and write to the C++ stream.
9 /// Return zero on success, non-zero on failure.
10 int read_py_write_cpp(Py_ssize_t number_of_bytes, std::iostream &ios);
11
12 /// Read from a C++ stream and write to a Python file.
13 /// Return zero on success, non-zero on failure.
14 int read_cpp_write_py(std::iostream &ios, Py_ssize_t number_of_bytes);
15
16 /// Read a number of bytes from a Python file and load them into the result.
17 /// Return zero on success, non-zero on failure.
18 int read(Py_ssize_t number_of_bytes, std::vector<char> &result);
19
20 /// Write a number of bytes to a Python file.
21 /// Return zero on success, non-zero on failure.
22 int write(const char *buffer, Py_ssize_t number_of_bytes);
23
24 /// Move the file pointer to the given position.
25 /// whence is:
26 /// 0 – start of the stream (the default); offset should be zero or positive.
27 /// 1 – current stream position; offset may be negative.
28 /// 2 – end of the stream; offset is usually negative.
29 /// Returns the new absolute position.
30 long seek(Py_ssize_t pos, int whence = 0);
31
32 /// Returns the current absolute position.
33 long tell();
34 /// Returns a multi-line string that describes the class state.
35 std::string str_pointers();
36 /// Returns a Python multi-line bytes object that describes the class state.
37 PyObject *py_str_pointers();
38 /// Destructor, this decrements the held references.
39 virtual ~PythonFileObjectWrapper();
40
41protected:
42 PyObject *m_python_file_object = NULL;
43 PyObject *m_python_read_method = NULL;
44 PyObject *m_python_write_method = NULL;
45 PyObject *m_python_seek_method = NULL;
46 PyObject *m_python_tell_method = NULL;
47};
Some example code is in src/cpy/cFile.cpp:
1/**
2 * Wraps a Python file object.
3 */
4static PyObject *
5wrap_python_file(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
6 assert(!PyErr_Occurred());
7 static const char *kwlist[] = {"file_object", NULL};
8 PyObject *py_file_object = NULL;
9
10 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", (char **) (kwlist),
11 &py_file_object)) {
12 return NULL;
13 }
14 PythonFileObjectWrapper py_file_wrapper(py_file_object);
15
16 /* Exercise ths wrapper by writing, reading etc. */
17 py_file_wrapper.write("Test write to python file", 25);
18 return py_file_wrapper.py_str_pointers();
19}
And some tests are in tests/unit/test_c_file.py:
1def test_wrap_python_file():
2 file = io.BytesIO()
3 result = cFile.wrap_python_file(file)
4 print()
5 print(' Result '.center(75, '-'))
6 print(result.decode('ascii'))
7 print(' Result DONE '.center(75, '-'))
8 print(' file.getvalue() '.center(75, '-'))
9 get_value = file.getvalue()
10 print(get_value)
11 print(' file.getvalue() DONE '.center(75, '-'))
12 assert get_value == b'Test write to python file'