Interrupt Python C API

Piet van Oostrum piet at
Wed Apr 15 13:31:40 CEST 2009

>>>>> googler.1.webmaster at (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):

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

signal.signal(signal.SIGALRM, handler)

def execute(command, timeout):
    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>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list