Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Monday, March 19, 2007

thread control clean

An example of an idiom for controling threads

Doug Fort
http://www.dougfort.net
"""

import threading

class TestThread(threading.Thread):
"""
A sample thread class
"""

def __init__(self):
"""
Constructor, setting initial variables
"""
self._stopevent = threading.Event()
self._sleepperiod = 1.0

threading.Thread.__init__(self, name="TestThread")

def run(self):
"""
overload of threading.thread.run()
main control loop
"""
print "%s starts" % (self.getName(),)

count = 0
while not self._stopevent.isSet():
count += 1
print "loop %d" % (count,)
self._stopevent.wait(self._sleepperiod)

print "%s ends" % (self.getName(),)

def join(self,timeout=None):
"""
Stop the thread
"""
self._stopevent.set()
threading.Thread.join(self, timeout)

if __name__ == "__main__":
testthread = TestThread()
testthread.start()

import time
time.sleep(10.0)

testthread.join()

Monday, February 26, 2007

How to do form.fill

suppose you have a form like:

form = web.form.Form(
web.form.Textbox('name', description='Name'),
web.form.Textbox('subject', description='Subject'),
web.form.Textarea('body', description='Message'),
)

You can pass a dictionary mapping values to form objects like:

form.fill(
{
'subject':'This is my subject!',
'body':t'This is the body!',
}
)

and these values will fill your textboxes.

Friday, February 16, 2007

urlparse(url, scheme='', allow_fragments=1)

this is what we should use urlparse(url, scheme='', allow_fragments=1)
Parse a URL into 6 components:
:///;?#
Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes.

Tuesday, January 09, 2007

Static variables in python

ints are not modifiable, so += actually rebinds the variable.  Try:

def_f():
global global_var_c_hits
global_var_c_hits +=1

Wednesday, December 27, 2006

index of max value in a list PYTHON

the max function, it returns the maximum value in the
list rather than the index associated with that value.

How do I return the index?


l.index(max(l)

l.index(max(l)) will give you the index of the first occurrance of the
maximum.

m = max(l)
[ i for i,v in enumerate(l) if v==m ]

will give you a list of all indices where the max occurs. (Putting the
'max(l)' outside the list comprehension prevents it from being evaluated
for each loop element.)