Interrupt Python C API

Piet van Oostrum piet at cs.uu.nl
Wed Apr 15 07:31:40 EDT 2009


>>>>> googler.1.webmaster at spamgourmet.com (g) wrote:

>g> Hi,
>g> I just have a design problem and don't know how to solve it. I call a
>g> function which
>g> executes a simple "PyRun_String(...)" command.

>g> imagine the script while 1: pass is executed so the app would hang. Is
>g> there any chance
>g> to break out this PyRun_String-function? I just searched the forums
>g> for that stuff
>g> but these information are very rare.

>g> Thanks for any suggestions.

I think PyRun_String is similar to exec. If you are on a Unix system you
can use the alarm signal. Here is a pure Python example, but I suspect
you can translate this to C in a straightforward manner.

import signal

class AlarmError(Exception):
    pass

def handler(signum, frame):
    raise AlarmError, "command lasts too long"

signal.signal(signal.SIGALRM, handler)

def execute(command, timeout):
    signal.alarm(timeout); 
    try:
        exec(command)
    except AlarmError, e:
        print e
        print 'Aborted "%s"' % (command,)
    print "continue work"

print "The everlasting command"
execute("while 1: pass", 10)
print "The End"


-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list