TP 7 : dibbler.py

Python Source icon dibbler.py — Python Source, 1 kB (1415 bytes)

Contenu du fichier

#!/usr/bin/python
import os, sys, select, time, random

root = 'dibbler.dir'
tmpfile = 'dibbler.tmp'
count = 100
dirfudge = 0.2
delay = 1
timeout = 10

if not os.path.isdir(root):
	os.mkdir(root)
if os.listdir(root):
	print "Warning : %s not empty"%repr(root)

class client:
	def handle_read(self): 
		pass

def log(msg):
	print >>sys.stderr, msg

def check_clients(deadline):
	while time.time() < deadline:
		rfds, wfds, efds = select.select(clients, [], [], max(deadline-time.time(),0))
		for client in rfds:
			client.handle_read()

def make_directory():
	rootdir = random.choice(dirs)
	dirname = "%f"%random.random()
	dirpath = os.path.join(rootdir, dirname)
	try:
		log("Creating directory : %s"%repr(dirpath))
		os.mkdir(dirpath)
		dirs.append(dirpath)
	except:
		print "Could not make "+repr(dirname)

def make_pebble(i):
	rootdir = random.choice(dirs)
	filename = str(i)
	filepath = os.path.join(rootdir, filename)
	value = "%03d"%random.randint(0,999)
	log("Creating file : %s (data : %s)"%(repr(filepath), value))
	f = open(tmpfile,"w")
	f.write(value)
	f.close()
	pebbles[i]=value
	os.rename(tmpfile, filepath)

i = 1
pebbles = {}
dirs = [root]
clients = []
next = time.time()
while i<count:
	check_clients(next)
	if random.random()<dirfudge:
		make_directory()
	else:
		make_pebble(i)
		i += 1
	next += delay
next += timeout
log("Waiting %d second(s) before exitting..."%timeout)
check_clients(next)

	

Newsletter