Terminating an embedded interpreter

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 12 13:08:22 CEST 2011

Ulrich Eckhardt wrote:

> Hi!
> I'm trying to provide some scripting capabilities to a program. For that,
> I'm embedding a Python interpreter, running a script in a separate thread
> to decouple it from the UI.
> Now, how should I handle rogue scripts? For example, when a script hangs
> in an endless loop, how do I signal the Python interpreter to shut down?

If you are using threads, they all run within the same Python process. You
can ask a thread to shut down, but you can't force it to from the outside.
If the thread runs a script that goes rogue, the script may never return
control to the thread long enough for it to respond to your request.

The main UI loop can still kill itself, and take all the threads with it, by
calling sys.exit. Or if you really need to, os.abort or os._exit can be
used for immediate "terminate yourself NOW!!!" commands. (But read the docs
for them first.)

A better way may be to run the script in a separate process. You can kill
the process the same way you would any other rogue process: by sending it a
signal. See the os and subprocess modules.

But Python's sandboxing abilities are not great. If you really fear rogue,
or malicious, scripts, perhaps Python is not the right language for this
task. Otherwise, just trust the script to be sane.


More information about the Python-list mailing list