User Tools

Site Tools


doc:appunti:prog:python_flock

Locking di un file in Python

Come bloccare un file in modo esclusivo prima di scriverlo. Il tentativo di lock è non-bloccante, se fallisce per diversi secondi il programma gestisce l'errore.

#!/usr/bin/python
import fcntl, re, sys, time
 
userdb = open("/etc/courier/userdb", "r")
htpasswd = open("/etc/apache2/htpasswd", "w")
lock = False
for t in range(5):
    try:
        fcntl.lockf(htpasswd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except:
        time.sleep(1)
    else:
        lock = True
        break
 
if not lock:
    sys.stderr.write("ERROR: cannot lock file /etc/apache2/htpasswd for writing.\n")
    sys.exit(1)
 
for line in userdb:
    htpasswd.write(line)
 
fcntl.lockf(htpasswd, fcntl.LOCK_UN)
htpasswd.close()
doc/appunti/prog/python_flock.txt · Last modified: 2010/12/02 12:20 by niccolo