From: Bartosz Golaszewski Date: Wed, 16 May 2018 10:18:40 +0000 (+0200) Subject: bindings: python: add support for controlled execution X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=2dfb43260a8d785282f2dd94c6f5bd9091a84fd3;p=qemu-gpiodev%2Flibgpiod.git 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 --- diff --git a/bindings/python/examples/gpiod_tests.py b/bindings/python/examples/gpiod_tests.py index 3fd3cb2..91ea961 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 1bf8de7..8676045 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) { @@ -1664,6 +1681,18 @@ static PyMethodDef gpiod_Chip_methods[] = { .ml_flags = METH_NOARGS, .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,