[Tutor] lockfiles and timestamps and nested if's!
Roeland Rengelink
r.b.rigilink@chello.nl
Fri, 18 May 2001 00:51:37 +0200
kromag@nsacom.net wrote:
>
> I am attempting a silly thing. I wish to make a script that will:
>
> 1. Check for the existence of a lockfile.
> 2. Check the age of the lockfile.
>
> Then either:
> Delete the lockfile if it is too old and continue,
> or
> exit gracefully.
>
> I have managed to get myself into a dither here. The script for some reason
> always writes a new lock file and updates the timestamp. Can someone clue me
> in? My brain is full.
>
> import glob
> import time
> import string
> import os
> import socket
>
> now=time.time()
> mybox=socket.gethostname()+'.txt'
> whoa=glob.glob('\tmp\*')
print whoa here, to see if the next test makes sense.
use os.listdir in stead of glob
> if whoa==['\tmp\'+mybox]:
> lockfile=open('\tmp\'+mybox, 'r')
> timestamp=lockfile.readline()
> print timestamp
> lockfile.close()
> if timestamp > time.time()-10:
You are comparing the string timestamp with the float time.time
Are you sure you want to delete lockfiles older than 10 seconds?
> print 'old lockfile ok',
> else:
> os.remove('\tmp\'+mybox)
>
Are you sure the lockfile shouldn't be recreated now?
> else:
The easiest way to end up here is if there's more than one file in \tmp\
> lockfile=open('\tmp\'+mybox, 'w')
> lockfile.write(`now`)
> print 'new lockfile'
> print 'and contiue with the rest of this balderdash!
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
OK here's what I understand you want to do:
import time, os, socket,
import string
now = time.time()
lockfilename = socket.gethostname()+'.txt'
if lockfilename in os.listdir('/tmp'):
contents = open('/tmp/'+lockfilename,'r').readline()
timestamp = float(string.strip(contents))
# use contents.strip() in Python2.0
if timestamp < now-10:
# the timestamp is old, we have to rewrite the file
# I'm not sure if this is actually what you want to do here
f = open('/tmp/'+lockfilename,'w')
f.write(str(now)+'\n')
else:
# the file doesn't exist at all, we have to write it
f = open('/tmp/'+lockfilename,'w')
f.write(str(now)+'\n')
Hmm. two code blocks doing the same thing is ugly
Maybe
- put lockfile creation and lockfile checking in functions ?
- use exceptions ?
Ah, this works anyway.
Hope this helps,
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"