From 50b645d48f4f66466488d3666b754bd936b7c964 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:00:27 +0000 Subject: [PATCH 1/2] Add build-python-c-extension-module materials folder --- build-python-c-extension-module/README.md | 55 +++++++++++++++ build-python-c-extension-module/fputs_demo.py | 25 +++++++ build-python-c-extension-module/fputsmodule.c | 68 +++++++++++++++++++ .../requirements.txt | 1 + build-python-c-extension-module/setup.py | 16 +++++ build-python-c-extension-module/test_fputs.py | 11 +++ build-python-c-extension-module/write_file.c | 8 +++ 7 files changed, 184 insertions(+) create mode 100644 build-python-c-extension-module/README.md create mode 100644 build-python-c-extension-module/fputs_demo.py create mode 100644 build-python-c-extension-module/fputsmodule.c create mode 100644 build-python-c-extension-module/requirements.txt create mode 100644 build-python-c-extension-module/setup.py create mode 100644 build-python-c-extension-module/test_fputs.py create mode 100644 build-python-c-extension-module/write_file.c diff --git a/build-python-c-extension-module/README.md b/build-python-c-extension-module/README.md new file mode 100644 index 0000000000..45a1de931d --- /dev/null +++ b/build-python-c-extension-module/README.md @@ -0,0 +1,55 @@ +# Building a Python C Extension Module + +This folder contains the sample code for the Real Python tutorial [Building a Python C Extension Module](https://realpython.com/build-python-c-extension-module/). + +## Files + +- `write_file.c`: the plain C program that calls `fputs()` +- `fputsmodule.c`: the finished `fputs` extension module, with the custom `StringTooShortError` exception, the `fopen()` error check, and the `FPUTS_FLAG` and `FPUTS_MACRO` constants +- `setup.py`: the `setuptools` build script for the module +- `fputs_demo.py`: the REPL examples from the tutorial as a script +- `test_fputs.py`: the `pytest` test for the module + +## Setup + +You need Python 3.10 or later, a C compiler, and the Python development headers. On Debian and Ubuntu, install `build-essential` and `python3-dev`. On Fedora, install `gcc` and `python3-devel`. On macOS, run `xcode-select --install`. + +Create and activate a virtual environment, then build and install the module from this folder: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install . +(venv) $ python -m pip install -r requirements.txt +``` + +## Usage + +Compile and run the plain C program: + +```console +$ gcc write_file.c -o write_file +$ ./write_file +$ cat write.txt +Real Python! +``` + +Run the examples: + +```console +(venv) $ python fputs_demo.py +'Python interface for the fputs C library function' +'fputs' +1 +Real Python! +64 +256 +StringTooShortError: String length must be greater than 10 +FileNotFoundError: [Errno 2] No such file or directory: '/nonexistent/write.txt' +``` + +Run the test: + +```console +(venv) $ pytest -q +``` diff --git a/build-python-c-extension-module/fputs_demo.py b/build-python-c-extension-module/fputs_demo.py new file mode 100644 index 0000000000..ad4e835c78 --- /dev/null +++ b/build-python-c-extension-module/fputs_demo.py @@ -0,0 +1,25 @@ +import fputs + +print(repr(fputs.__doc__)) +print(repr(fputs.__name__)) + +# Write to an empty file named `write.txt` +print(fputs.fputs("Real Python!", "write.txt")) +with open("write.txt", "r") as f: + print(f.read()) + +# Constants +print(fputs.FPUTS_FLAG) +print(fputs.FPUTS_MACRO) + +# Custom exception +try: + fputs.fputs("RP!", "write.txt") +except fputs.StringTooShortError as error: + print(f"{type(error).__name__}: {error}") + +# OSError from a file that can't be opened +try: + fputs.fputs("Real Python!", "/nonexistent/write.txt") +except OSError as error: + print(f"{type(error).__name__}: {error}") diff --git a/build-python-c-extension-module/fputsmodule.c b/build-python-c-extension-module/fputsmodule.c new file mode 100644 index 0000000000..6ab64a0a57 --- /dev/null +++ b/build-python-c-extension-module/fputsmodule.c @@ -0,0 +1,68 @@ +#include + +static PyObject *StringTooShortError = NULL; + +static PyObject *method_fputs(PyObject *self, PyObject *args) { + char *str, *filename = NULL; + int bytes_copied = -1; + + /* Parse arguments */ + if(!PyArg_ParseTuple(args, "ss", &str, &filename)) { + return NULL; + } + + if (strlen(str) < 10) { + /* Passing custom exception */ + PyErr_SetString(StringTooShortError, + "String length must be greater than 10"); + return NULL; + } + + FILE *fp = fopen(filename, "w"); + if (fp == NULL) { + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename); + } + + bytes_copied = fputs(str, fp); + fclose(fp); + + return PyLong_FromLong(bytes_copied); +} + +static PyMethodDef FputsMethods[] = { + {"fputs", method_fputs, METH_VARARGS, + "Python interface for fputs C library function"}, + {NULL, NULL, 0, NULL} +}; + + +static struct PyModuleDef fputsmodule = { + PyModuleDef_HEAD_INIT, + "fputs", + "Python interface for the fputs C library function", + -1, + FputsMethods +}; + +PyMODINIT_FUNC PyInit_fputs(void) { + /* Assign module value */ + PyObject *module = PyModule_Create(&fputsmodule); + + /* Initialize new exception object */ + StringTooShortError = PyErr_NewException("fputs.StringTooShortError", + NULL, NULL); + + /* Add exception object to your module */ + PyModule_AddObjectRef(module, "StringTooShortError", StringTooShortError); + + /* Add int constant by name */ + PyModule_AddIntConstant(module, "FPUTS_FLAG", 64); + + /* Define int macro */ + #define FPUTS_MACRO 256 + + /* Add macro to module */ + PyModule_AddIntMacro(module, FPUTS_MACRO); + + return module; +} diff --git a/build-python-c-extension-module/requirements.txt b/build-python-c-extension-module/requirements.txt new file mode 100644 index 0000000000..3fdf1e14fe --- /dev/null +++ b/build-python-c-extension-module/requirements.txt @@ -0,0 +1 @@ +pytest==9.2.0 diff --git a/build-python-c-extension-module/setup.py b/build-python-c-extension-module/setup.py new file mode 100644 index 0000000000..c4936c986a --- /dev/null +++ b/build-python-c-extension-module/setup.py @@ -0,0 +1,16 @@ +from setuptools import setup, Extension + + +def main(): + setup( + name="fputs", + version="1.0.0", + description="Python interface for the fputs C library function", + author="", + author_email="your_email@gmail.com", + ext_modules=[Extension("fputs", ["fputsmodule.c"])], + ) + + +if __name__ == "__main__": + main() diff --git a/build-python-c-extension-module/test_fputs.py b/build-python-c-extension-module/test_fputs.py new file mode 100644 index 0000000000..8c6bb85972 --- /dev/null +++ b/build-python-c-extension-module/test_fputs.py @@ -0,0 +1,11 @@ +import fputs + + +def test_copy_data(): + content_to_copy = "Real Python!" + fputs.fputs(content_to_copy, "test_write.txt") + + with open("test_write.txt", "r") as f: + content_copied = f.read() + + assert content_copied == content_to_copy diff --git a/build-python-c-extension-module/write_file.c b/build-python-c-extension-module/write_file.c new file mode 100644 index 0000000000..581f17bbf1 --- /dev/null +++ b/build-python-c-extension-module/write_file.c @@ -0,0 +1,8 @@ +#include + +int main() { + FILE *fp = fopen("write.txt", "w"); + fputs("Real Python!", fp); + fclose(fp); + return 0; +} From ba46b80f1d3739dec3f57f56c2eab31de377383a Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:02:52 +0000 Subject: [PATCH 2/2] Wrap long line in fputsmodule.c --- build-python-c-extension-module/fputsmodule.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build-python-c-extension-module/fputsmodule.c b/build-python-c-extension-module/fputsmodule.c index 6ab64a0a57..043713e965 100644 --- a/build-python-c-extension-module/fputsmodule.c +++ b/build-python-c-extension-module/fputsmodule.c @@ -53,7 +53,8 @@ PyMODINIT_FUNC PyInit_fputs(void) { NULL, NULL); /* Add exception object to your module */ - PyModule_AddObjectRef(module, "StringTooShortError", StringTooShortError); + PyModule_AddObjectRef(module, "StringTooShortError", + StringTooShortError); /* Add int constant by name */ PyModule_AddIntConstant(module, "FPUTS_FLAG", 64);