[Tutor] Stop a long loop in python console or in wxpython?
alan.gauld at btinternet.com
Mon Jun 8 10:23:08 CEST 2009
"xbmuncher" <xboxmuncher at gmail.com> wrote
> def longLoop():
> x = 0
> for n in range(100000):
> x = x + n
> It will run in the console for a long time. How can I send a command and
> cause it to stop and pursue hello() function?
You can use Ctrl-C and put the loop insiode a try/except clause
to catch the Interrupt. Or....
> in the console.. and really I'd like to create a GUI that will run the
> longLoop() function after I push a button and then press another button
> stop the longLoop() function and run the hello() function.
There are two normal ways to do this in a GUI:
1) break the loop into small chunks and run them in response
to timer events. The function then calls the timer at the end of
each chunk until it completes its task. This frees up the GUI to
detect user events between timers.
2) Use threads. This has the advantage of working in a GUI
or a commandline. But is a little bit more complex and you
need to make sure your loop isn't messing with (or being
messed with) the rest of the priogram via shared data/resources.
> in the wxPython, which is gui of choice for python. I'll settle for a way
> do it via console as well. The overall idea is, is that I want to cut
> the process of a piece of code in order to start another piece of code.
You can put a terminating flag in the timer code or you can
send a message to stop a thread, either way will work.
Author of the Learn to Program web site
More information about the Tutor