aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBartosz Golaszewski <bartekgola@gmail.com>2018-05-16 12:18:40 +0200
committerBartosz Golaszewski <bartekgola@gmail.com>2018-05-16 12:29:17 +0200
commit2dfb43260a8d785282f2dd94c6f5bd9091a84fd3 (patch)
tree537fb08a50faae9a8081e8a27d3b8a408cb6ec0f
parente04d4d45c200e0e1277ca1c74e0f7f56d700b9c9 (diff)
downloadlibgpiod-2dfb43260a8d785282f2dd94c6f5bd9091a84fd3.tar.gz
bindings: python: add support for controlled execution
Provide __enter__ and __exit__ callbacks for Chip so that it can be used with the 'with' statement. Signed-off-by: Bartosz Golaszewski <bartekgola@gmail.com>
-rwxr-xr-xbindings/python/examples/gpiod_tests.py8
-rw-r--r--bindings/python/gpiodmodule.c29
2 files changed, 37 insertions, 0 deletions
diff --git a/bindings/python/examples/gpiod_tests.py b/bindings/python/examples/gpiod_tests.py
index 3fd3cb2b..91ea9612 100755
--- a/bindings/python/examples/gpiod_tests.py
+++ b/bindings/python/examples/gpiod_tests.py
@@ -102,6 +102,14 @@ def chip_use_after_close():
add_test('Use a GPIO chip after closing it', chip_use_after_close)
+def chip_with_statement():
+ with gpiod.Chip('gpiochip0') as chip:
+ print('Chip name in controlled execution: {}'.format(chip.name()))
+ line = chip.get_line(3)
+ print('Got line from chip in controlled execution: {}'.format(line.name()))
+
+add_test('Use a GPIO chip in controlled execution', chip_with_statement)
+
def chip_info():
chip = gpiod.Chip('gpiochip0')
print('name: {}'.format(chip.name()))
diff --git a/bindings/python/gpiodmodule.c b/bindings/python/gpiodmodule.c
index 1bf8de7b..86760450 100644
--- a/bindings/python/gpiodmodule.c
+++ b/bindings/python/gpiodmodule.c
@@ -1315,6 +1315,23 @@ static PyObject *gpiod_Chip_close(gpiod_ChipObject *self)
Py_RETURN_NONE;
}
+PyDoc_STRVAR(gpiod_Chip_enter_doc,
+"Controlled execution enter callback.");
+
+static PyObject *gpiod_Chip_enter(gpiod_ChipObject *chip)
+{
+ Py_INCREF(chip);
+ return (PyObject *)chip;
+}
+
+PyDoc_STRVAR(gpiod_Chip_exit_doc,
+"Controlled execution exit callback.");
+
+static PyObject *gpiod_Chip_exit(gpiod_ChipObject *chip)
+{
+ return PyObject_CallMethod((PyObject *)chip, "close", "");
+}
+
static bool gpiod_ChipIsClosed(gpiod_ChipObject *chip)
{
if (!chip->chip) {
@@ -1665,6 +1682,18 @@ static PyMethodDef gpiod_Chip_methods[] = {
.ml_doc = gpiod_Chip_close_doc,
},
{
+ .ml_name = "__enter__",
+ .ml_meth = (PyCFunction)gpiod_Chip_enter,
+ .ml_flags = METH_NOARGS,
+ .ml_doc = gpiod_Chip_enter_doc,
+ },
+ {
+ .ml_name = "__exit__",
+ .ml_meth = (PyCFunction)gpiod_Chip_exit,
+ .ml_flags = METH_VARARGS,
+ .ml_doc = gpiod_Chip_exit_doc,
+ },
+ {
.ml_name = "name",
.ml_meth = (PyCFunction)gpiod_Chip_name,
.ml_flags = METH_NOARGS,