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

2008/08/25

Examples of Python threading and Queue

#!/usr/bin/env python
import threading,Queue,random,time,sys

class th(threading.Thread):

def __init__(self,threadName,queue):
threading.Thread.__init__(self,name=threadName)
self.name=threadName
self.Q=queue
print 'Name: %s started.'%(self.getName())

def run(self):
while 1:
num=self.Q.get(1)
if num==-1:
self.Q.task_done()
break
else:
print '%s sleep %f'%(self.name,num)
time.sleep(num)
print '%s wake after %f'%(self.name,num)
self.Q.task_done()
print '%s finish.'%self.name

thnum=2
Q=Queue.Queue(thnum*2)
for t1 in range(thnum):
th('thread%d'%t1,Q).start()

for t1 in range(10):
Q.put(random.random(),1)

for t1 in range(thnum):
Q.put(-1,1)
print 'wait...'
Q.join()


Do not forget to call Q.task_done() after each run of thread. Otherwise, Q.join() will be waiting for ever.

2008/07/08

Exec and eval in python

Example:
exec('a=1+3')
or
a=eval('1+3')
then a=4

Set environment variables in python

client.py

#!/usr/bin/env python

import os,datetime

starttimestr=datetime.datetime.now().strftime('%Y%m%d%M%S')

os.environ['starttime']=starttimestr

os.system('t1.sh')

t1.sh

#!/bin/bash

echo $starttime

runt1.py

#!/usr/bin/env python

import os,datetime

starttime=datetime.datetime.strptime(os.environ['starttime'],'%Y%m%d%M%S')

print starttime

environment variables can be transferred in this way. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). Availability: most flavors of Unix, Windows.