exec code with timeout?

Paul Moore pf_moore at yahoo.co.uk
Mon Sep 8 23:18:12 CEST 2003


Paul Moore <pf_moore at yahoo.co.uk> writes:

> If
>    1. You run the code you want to interrupt in the main thread
>    2. You don't mind the interrupt being a KeyboardInterrupt exception
>
> then you can write the code in pure Python, as follows:

A module to wrap PyThreadState_SetAsyncExc isn't exactly hard, either.
Here's one in its entirety (async.c). I'm not sure I believe the
argument in the reference manual that this function is not exposed to
Python to avoid accidental mistakes - why not expose it, but with a
suitably "internal" name, and documentation warnings (much like
sys._getframe). It could easily be thread._async_exc(), for example.

Anyway, here's the code if it's of any interest...

Paul

#include <Python.h>

static PyObject *
async_exc(PyObject *self, PyObject *args)
{
    PyObject *exc;
    int id;
    int n;

    if (!PyArg_ParseTuple(args, "iO:async_exc", &id, &exc))
        return NULL;

    n = PyThreadState_SetAsyncExc(id, exc);
    if (n > 1) {
        /* Problem - clear the exception... */
        PyThreadState_SetAsyncExc(id, NULL);
	return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef ModuleMethods[] = {
    {"async_exc",  async_exc, METH_VARARGS,
     "Raise an exception in the given thread."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC
initasync(void)
{
    Py_InitModule("async", ModuleMethods);
}

-- 
This signature intentionally left blank




More information about the Python-list mailing list