Using signal.alarm to terminate a thread
Nick Craig-Wood
nick at craig-wood.com
Mon Nov 13 07:30:03 EST 2006
Adrian Casey <adrian.casey at internode.on.net> wrote:
> I have a multi-threaded python application which uses pexpect to connect to
> multiple systems concurrently. Each thread within my application is a
> connection to a remote system. The problem is when one of the child
> threads runs a command which generates an unlimited amount of output. The
> classic example of this is the "yes" command. If you
> execute "pexpect.run('yes')", your cpu will sit at 100% forever.
>
> Here is a simple multi-threaded program using pexpect which demonstrates the
> problem. The command 'yes' is run in a thread. The parent says that when
> the alarm goes off, run the handler function. The thread sets the alarm to
> trigger after 5 seconds.
1) Don't ever mix threads and signals - you are heading for trouble!
2) pexpect has a timeout parameter exactly for this case
import os, pexpect, threading
def runyes():
print "Running yes command..."
pexpect.run('yes', timeout=5)
t = threading.Thread(target=runyes)
t.start()
t.join()
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list