From 214dd69400997f9cd4ce6e89d836cf2e1a806cca Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Wed, 7 Oct 2020 19:14:37 +0200 Subject: [PATCH] Add wrapper for PyErr_CheckSignals() to Python. This is a useful API in long-running Rust code, which lets users cancel evaluation by pressing Ctrl-C, and run any other signal handlers that have been set using the signal module. --- src/python.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/python.rs b/src/python.rs index 88c372b8046..55eaa69dbe7 100644 --- a/src/python.rs +++ b/src/python.rs @@ -498,6 +498,21 @@ impl<'p> Python<'p> { pub fn xdecref(self, ptr: T) { unsafe { ffi::Py_XDECREF(ptr.into_ptr()) }; } + + /// Lets the Python interpreter check for pending signals and invoke the + /// corresponding signal handlers. This can run arbitrary Python code. + /// + /// If an exception is raised by the signal handler, or the default signal + /// handler raises an exception (such as `KeyboardInterrupt` for `SIGINT`), + /// an `Err` is returned. + pub fn check_signals(self) -> PyResult<()> { + let v = unsafe { ffi::PyErr_CheckSignals() }; + if v == -1 { + Err(PyErr::fetch(self)) + } else { + Ok(()) + } + } } #[cfg(test)]