473,383 Members | 1,885 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Is there a better way to implement this:

Hello:

I wrote the code below (much irrelevant code removed).
This doesn't quite work. What I wanted it to do was
a) Execute function ftimed, which takes a function and a timeout
in seconds.
b) This will also execute function abort() as a thread.
This function just runs for the specified
number of seconds and returns.
However, before it returns, throws an exception.
c) If test() is still running when abort() is
finished, ftimed() should catch the exception and
return.

It is catching the exception, however it continues running the function.
Why does it continue and not return?

What am I missing, or is there a better way to
implement this (having ftimed() return when the
abort-timer time is exceeded?
import time, thread, sys

thread_finished = "MAX RUN TIME EXCEEDED!"

def abort (seconds):
start_time = time.time()
while ((time.time() - start_time) < seconds):
time.sleep(0.01)
print "script run time exceeded max_run_time of", seconds, "seconds."
raise thread_finished
return
def test():
i = 0
while (True):
time.sleep(1)
print "HELLO", i
i+=1
def ftimed (func, seconds):
thread.start_new_thread (abort, (seconds,))

try:
func()
except thread_finished:
print "Timeout"
return

ftimed (test, 30)
print "Script finished"

It presently generates the following output:
$ python ./testthread.py
HELLO 0
HELLO 1
HELLO 2
HELLO 3
HELLO 4
HELLO 5
HELLO 6
HELLO 7
HELLO 8
HELLO 9
HELLO 10
HELLO 11
HELLO 12
HELLO 13
HELLO 14
HELLO 15
HELLO 16
HELLO 17
HELLO 18
HELLO 19
HELLO 20
HELLO 21
HELLO 22
HELLO 23
HELLO 24
HELLO 25
HELLO 26
HELLO 27
HELLO 28
HELLO 29
script run time exceeded max_run_time of 30 seconds.
Unhandled exception in thread started by <function abort at 0x009CEF30>
Traceback (most recent call last):
File "./testthread.py", line 10, in abort
raise thread_finished
MAX RUN TIME EXCEEDED!
HELLO 30
HELLO 31
HELLO 32
.....

Thanks in advance:
Michael Yanowitz
Jan 22 '07 #1
3 1306
Michael Yanowitz wrote:
Hello:

I wrote the code below (much irrelevant code removed).
This doesn't quite work. What I wanted it to do was
a) Execute function ftimed, which takes a function and a timeout
in seconds.
b) This will also execute function abort() as a thread.
This function just runs for the specified
number of seconds and returns.
However, before it returns, throws an exception.
c) If test() is still running when abort() is
finished, ftimed() should catch the exception and
return.

It is catching the exception, however it continues running the function.
Why does it continue and not return?
The exception is raised in the thread that executes the abort() function.
The exception does not get caught and terminates this thread. The other
(main) thread is unaffected - exceptions are local to a thread and there is
currently no (portable) way to raise an exception in another thread.
What am I missing, or is there a better way to
implement this (having ftimed() return when the
abort-timer time is exceeded?
You may use the signal.alarm() function, if you are on a UNIXoid system and
you have only a signle time-out at a time (e.g. not nested).
import time, thread, sys

thread_finished = "MAX RUN TIME EXCEEDED!"

def abort (seconds):
start_time = time.time()
while ((time.time() - start_time) < seconds):
time.sleep(0.01)
any reason for not using time.sleep(seconds) here?
print "script run time exceeded max_run_time of", seconds, "seconds."
raise thread_finished
return
def test():
i = 0
while (True):
time.sleep(1)
print "HELLO", i
i+=1
def ftimed (func, seconds):
thread.start_new_thread (abort, (seconds,))

try:
func()
except thread_finished:
print "Timeout"
return

ftimed (test, 30)
print "Script finished"
--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
Jan 22 '07 #2
Michael Yanowitz wrote:
>
I guess I am looking for something portable (both
Windows and Linux) where I can abort a function after
a certain time limit expires.
Doing a search for "timeout function Python" on Google reveals a number
of approaches.

Using signals:

* http://nick.vargish.org/clues/python-tricks.html
* http://aspn.activestate.com/ASPN/Coo.../Recipe/307871

Using threads:

* http://aspn.activestate.com/ASPN/Coo.../Recipe/473878

Using processes:

* http://lfw.org/python/delegate.html

Paul

Jan 22 '07 #3
Paul Boddie wrote:
Michael Yanowitz wrote:
>>
I guess I am looking for something portable (both
Windows and Linux) where I can abort a function after
a certain time limit expires.

Doing a search for "timeout function Python" on Google reveals a number
of approaches.
Using threads:

* http://aspn.activestate.com/ASPN/Coo.../Recipe/473878
That doesn't abort the calculation, however -- it just moves on with a
default value instead of the actual result if that is not available after
the specified timespan.

The calculation may go on forever eating up resources.

Peter
Jan 23 '07 #4

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

Similar topics

1
by: sayoyo | last post by:
Hi Guys, I have to implement a design in Java which is a collection class gathers several units of the same class. I was thinking about two ways to implement it. the first is to create two...
220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
133
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
39
by: bazad | last post by:
Hi, I am not using C all the time. I have a general understanding of C and nothing else. The recent reply to use strlcpy and strlcat showed me that I am not aware of the best and safe...
3
by: Sai Kit Tong | last post by:
I posted for help on legacy code interface 2 days ago. Probably I didn't make it clear in my original mail. I got a couple of answers but none of them address my issues directly (See attached...
1
by: Mihajlo Cvetanovic | last post by:
Hi, I have to create a dll with communication functionality. The first idea was to implement only functions for sending, and user to implement (and pass me a pointer to) function for...
5
by: --== Alain ==-- | last post by:
Hi, Several months ago i've asked some information about the best way how to have some particular columns (progress bar, checkbox, images, color picker,...) in a ListView component. It seems...
1
by: Saba | last post by:
Which of the following is a better approach to implement generic algorithms ; overloading or templates? Justify with the help of examples.
20
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in...
26
by: Chris Becke | last post by:
Given an interface (in the c++ sense, nothing more than a struct containing pure virtual methods) struct Iv1 { virtual method0()=0; }; And a class that implements the interface class...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.