Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions build-python-c-extension-module/README.md
Original file line number Diff line number Diff line change
@@ -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
```
25 changes: 25 additions & 0 deletions build-python-c-extension-module/fputs_demo.py
Original file line number Diff line number Diff line change
@@ -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}")
69 changes: 69 additions & 0 deletions build-python-c-extension-module/fputsmodule.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#include <Python.h>

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;
}
1 change: 1 addition & 0 deletions build-python-c-extension-module/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==9.2.0
16 changes: 16 additions & 0 deletions build-python-c-extension-module/setup.py
Original file line number Diff line number Diff line change
@@ -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="<your name>",
author_email="your_email@gmail.com",
ext_modules=[Extension("fputs", ["fputsmodule.c"])],
)


if __name__ == "__main__":
main()
11 changes: 11 additions & 0 deletions build-python-c-extension-module/test_fputs.py
Original file line number Diff line number Diff line change
@@ -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
8 changes: 8 additions & 0 deletions build-python-c-extension-module/write_file.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include <stdio.h>

int main() {
FILE *fp = fopen("write.txt", "w");
fputs("Real Python!", fp);
fclose(fp);
return 0;
}
Loading