473,657 Members | 2,266 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to cleanly pause/stop a long running function?

Suppose I have a function that may run for a long time - perhaps from
several minutes to several hours. An example would be this file
processing function:

import os
def processFiles(st artDir):
for root, dirs, files in os.walk(startDi r):
for fname in files:
if fname.lower().e ndswith(".zip") :
# ... do interesting stuff with the file here ...

Imagine that there are thousands of files to process. This could take
a while. How can I implement this so that the caller can pause or
interrupt this function, and resume its program flow? Doing a Ctrl+C
interrupt would be a not-so-clean-way of performing such a thing, and
it would quit the application altogether. I'd rather have the function
return a status object of what it has accomplished thus far.

I have heard about threads, queues, and asynchronous programming, but
am not sure which is appropriate for this and how to apply it. Perhaps
the above function should be a method of a class that inherits from
the appropriate handler class? Any help will be appreciated.

-Basilisk96

May 12 '07 #1
3 5532
On May 12, 4:51 pm, Basilisk96 <basilis...@gma il.comwrote:
Suppose I have a function that may run for a long time - perhaps from
several minutes to several hours. An example would be this file
processing function:

import os
def processFiles(st artDir):
for root, dirs, files in os.walk(startDi r):
for fname in files:
if fname.lower().e ndswith(".zip") :
# ... do interesting stuff with the file here ...

Imagine that there are thousands of files to process. This could take
a while. How can I implement this so that the caller can pause or
interrupt this function, and resume its program flow? Doing a Ctrl+C
interrupt would be a not-so-clean-way of performing such a thing, and
it would quit the application altogether. I'd rather have the function
return a status object of what it has accomplished thus far.

I have heard about threads, queues, and asynchronous programming, but
am not sure which is appropriate for this and how to apply it. Perhaps
the above function should be a method of a class that inherits from
the appropriate handler class? Any help will be appreciated.

-Basilisk96
Consider using generators.
http://docs.python.org/tut/node11.ht...00000000000000

This way, whatever part of your program calls this function can
completely control the iteration. Maybe you can have it yield status
information each time.

May 13 '07 #2
On Sat, 12 May 2007 13:51:05 -0700, Basilisk96 wrote:
Suppose I have a function that may run for a long time - perhaps from
several minutes to several hours. An example would be this file
processing function:

import os
def processFiles(st artDir):
for root, dirs, files in os.walk(startDi r):
for fname in files:
if fname.lower().e ndswith(".zip") :
# ... do interesting stuff with the file here ...

Imagine that there are thousands of files to process. This could take
a while. How can I implement this so that the caller can pause or
interrupt this function, and resume its program flow?
I don't think there really is what I would call a _clean_ way, although
people may disagree about what's clean and what isn't.

Here's a way that uses global variables, with all the disadvantages that
entails:

last_dir_comple ted = None
restart = object() # a unique object

def processFiles(st artDir):
global last_dir_comple ted
if startDir is restart:
startDir = last_dir_comple ted
for root, dirs, files in os.walk(startDi r):
for fname in files:
if fname.lower().e ndswith(".zip") :
# ... do interesting stuff with the file here ...
last_Dir_comple ted = root

Here's another way, using a class. Probably not the best way, but a way.

class DirLooper(objec t):
def __init__(self, startdir):
self.status = "new"
self.startdir = startdir
self.root = startdir
def run(self):
if self.status == 'new':
self.loop(self. startdir)
elif self.status == 'finished':
print "nothing to do"
else:
self.loop(self. root)
def loop(self, where):
self.status = "started"
for self.root, dirs, files in os.walk(where):
# blah blah blah...
Here's another way, catching the interrupt:

def processFiles(st artDir):
try:
for root, dirs, files in os.walk(startDi r):
# blah blah blah ...
except KeyboardInterru pt:
do_something_wi th_status()
You can fill in the details :)
As for which is "better", I think the solution using a global variable is
the worst, although it has the advantage of being easy to implement. I
think you may need to try a few different implementations and judge for
yourself.
--
Steven.

May 13 '07 #3
Doing a Ctrl+C
interrupt would be a not-so-clean-way of performing such a thing, and
it would quit the application altogether. I'd rather have the function
return a status object of what it has accomplished thus far.
Just in case you are unaware that you can explicitly handle ^C in your
python code, look up the KeyboardInterru pt exception.

mt

May 13 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
15477
by: Jakub | last post by:
I have the following problem. Suppose I added a button to my worksheet and when user clicks the button a function starts. Now, as long as this function is running the worksheet is not active. The question is: is it possible to stop this function from the worksheet, for example is it possible to add another button to the worksheet so that the user could click this button and stop the function that is running after he clicked the first...
8
36442
by: Wim | last post by:
My GUI application starts a process (a console program) when the user hits Play. I would like to add an option to pause that process. The code I've added to detect if the user hit pause/unpause seems to work. But I have no clue how to pause/suspend the process. As far as I can see the Process class doesn't offer anything for this. So it's probably the thread the process is running on that should be suspended or put to sleep. But just...
38
3988
by: Jackie | last post by:
I just want the programme to stop for a while. Thanks.
0
1107
by: FaroeIslander | last post by:
Hello all. I am currently working on a program in VB.NET where the user can run a "hidden" DOS program and as the program is running the user can see how many computations have been performed by the program. To do this i am "piping" information back and forth between DOS and VB.NET. I also want to make the user able to abort and/or pause the computations in DOS. My question is how i can abort/pause a running DOS program. The only way to...
2
2269
by: eSolTec, Inc. 501(c)(3) | last post by:
Thank you in advance for any and all assistance. Is there a way to start, pause and resume a recurrsive search exactly where you left off, say in the registry programmatically? -- Michael Bragg, President eSolTec, Inc. a 501(C)(3) organization MS Authorized MAR looking for used laptops for developmentally disabled.
6
2277
by: Zytan | last post by:
I have code running in the debugger as I type. I press pause, and it pauses on: Application.Run(new myForm()); *I believe* a worker thread is in deadlock (it's in a lock, but calls another function that tries to use the same lock). If the main thread was deadlocked, I think the debugger would stop right on that spot. So, I assume that it is a worker thread that is deadlocked.
3
2611
by: garfunkel214 | last post by:
I have images and text rotating every 7000 ms using a setInterval. i am trying to implement a pause button that will stop the rotation when clicked. When clicked once more, I would like the rotation to continue. The first time that the pause button is clicked, the rotation stops and all is well. Click again and the rotation continues. But then i can't seem to pause thereafter. Where am i going wrong? function pause() { switch (p) {...
11
3500
nathj
by: nathj | last post by:
Hi, I have a strange problem, my code is running too quickly. Allow me to explain (if I can). I am using the XMLHTTP object in order to query the database as a user completes the membership application form, basically I want to ensure that each username is unique. I have the code to check this and the XMLHTTP object is working fine. However, before the code finishes executing the next part of the function is run. this means that the...
3
3231
by: nma | last post by:
Hi This code goes well with play, stop and fullscreen button, the only thing is the pause button is not there. How to make pause button? I try to make pause button but when it streams video, when I click pause, it stop but it work play again when i click at play button. Please help. <?php function printInstructions() { ?>
0
8407
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8319
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8512
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8612
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2739
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.